app.js 905 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083
  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.ospfLiveInterfaces || state.ospfTemplates || []).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
  9293. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  9294. : (inst.running
  9295. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  9296. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  9297. const redist = [];
  9298. if (inst.redistribute_connected) redist.push('conn');
  9299. if (inst.redistribute_static) redist.push('static');
  9300. if (inst.redistribute_bgp) redist.push('bgp');
  9301. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9302. redist.push('default');
  9303. }
  9304. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9305. const origBadge = origDef === 'always'
  9306. ? '<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>'
  9307. : (origDef === 'if-installed'
  9308. ? '<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>'
  9309. : '<span class="text-slate-500 text-[10px]">never</span>');
  9310. return `
  9311. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9312. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9313. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  9314. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9315. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9316. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9317. </td>
  9318. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9319. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9320. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9321. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9322. <td class="py-1.5 px-3">${origBadge}</td>
  9323. </tr>
  9324. `;
  9325. }).join('');
  9326. }
  9327. // TAB 2: AREAS
  9328. function renderOspfAreas() {
  9329. const tbody = document.getElementById('ospf-areas-table-body');
  9330. if (!tbody) return;
  9331. const countEl = document.getElementById('ospf-areas-footer-count');
  9332. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9333. let list = state.ospfAreas || [];
  9334. if (filter) {
  9335. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9336. }
  9337. if (countEl) countEl.innerText = list.length;
  9338. const selId = state.selectedOspfRow?.areas;
  9339. tbody.innerHTML = list.map((a, idx) => {
  9340. const isSel = a.id === selId;
  9341. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9342. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9343. return `
  9344. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9345. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9346. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9347. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9348. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9349. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9350. </td>
  9351. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9352. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9353. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9354. </tr>
  9355. `;
  9356. }).join('');
  9357. }
  9358. // TAB 3: AREA RANGES
  9359. function renderOspfAreaRanges() {
  9360. const tbody = document.getElementById('ospf-ranges-table-body');
  9361. if (!tbody) return;
  9362. const countEl = document.getElementById('ospf-ranges-footer-count');
  9363. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9364. let list = state.ospfAreaRanges || [];
  9365. if (filter) {
  9366. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9367. }
  9368. if (countEl) countEl.innerText = list.length;
  9369. const selId = state.selectedOspfRow?.['area-ranges'];
  9370. tbody.innerHTML = list.map((r, idx) => {
  9371. const isSel = r.id === selId;
  9372. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9373. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9374. return `
  9375. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9376. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9377. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9378. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9379. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9380. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9381. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9382. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9383. </tr>
  9384. `;
  9385. }).join('');
  9386. }
  9387. // TAB 4: INTERFACE TEMPLATES
  9388. function renderOspfTemplates() {
  9389. const tbody = document.getElementById('ospf-templates-table-body');
  9390. if (!tbody) return;
  9391. const countEl = document.getElementById('ospf-templates-footer-count');
  9392. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9393. let list = state.ospfTemplates || [];
  9394. if (filter) {
  9395. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9396. }
  9397. if (countEl) countEl.innerText = list.length;
  9398. const selId = state.selectedOspfRow?.templates;
  9399. tbody.innerHTML = list.map((t, idx) => {
  9400. const isSel = t.id === selId;
  9401. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9402. const ifaces = t.interfaces || t.interface || 'all';
  9403. const nets = t.networks || t.network || '';
  9404. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9405. return `
  9406. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9407. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9408. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9409. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9410. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9411. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9412. </td>
  9413. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9414. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9415. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9416. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9417. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9418. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9419. </tr>
  9420. `;
  9421. }).join('');
  9422. }
  9423. // TAB 5: LIVE INTERFACES
  9424. function renderOspfLiveInterfaces() {
  9425. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9426. if (!tbody) return;
  9427. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9428. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9429. let list = state.ospfLiveInterfaces || [];
  9430. if (filter) {
  9431. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9432. }
  9433. if (countEl) countEl.innerText = list.length;
  9434. tbody.innerHTML = list.map(i => `
  9435. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9436. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9437. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9438. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9439. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9440. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9441. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9442. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9443. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9444. </tr>
  9445. `).join('');
  9446. }
  9447. // TAB 6: STATIC NEIGHBORS
  9448. function renderOspfStaticNbrs() {
  9449. const tbody = document.getElementById('ospf-snbrs-table-body');
  9450. if (!tbody) return;
  9451. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9452. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9453. let list = state.ospfStaticNbrs || [];
  9454. if (filter) {
  9455. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9456. }
  9457. if (countEl) countEl.innerText = list.length;
  9458. const selId = state.selectedOspfRow?.['static-nbrs'];
  9459. tbody.innerHTML = list.map((n, idx) => {
  9460. const isSel = n.id === selId;
  9461. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9462. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9463. return `
  9464. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9465. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9466. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9467. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9468. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9469. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9470. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9471. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9472. </tr>
  9473. `;
  9474. }).join('');
  9475. }
  9476. // TAB 7: LIVE NEIGHBORS
  9477. function renderOspfNeighbors() {
  9478. const tbody = document.getElementById('ospf-neighbors-table-body');
  9479. if (!tbody) return;
  9480. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9481. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9482. let list = state.ospfNeighbors || [];
  9483. if (filter) {
  9484. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9485. }
  9486. if (countEl) countEl.innerText = list.length;
  9487. tbody.innerHTML = list.map(n => `
  9488. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9489. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9490. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9491. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9492. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9493. </td>
  9494. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9495. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9496. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9497. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9498. </tr>
  9499. `).join('');
  9500. }
  9501. // TAB 8: LINK-STATE DATABASE (LSA)
  9502. function renderOspfLSA() {
  9503. const tbody = document.getElementById('ospf-lsa-table-body');
  9504. if (!tbody) return;
  9505. const countEl = document.getElementById('ospf-lsa-footer-count');
  9506. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9507. let list = state.ospfLSA || [];
  9508. if (filter) {
  9509. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9510. }
  9511. if (countEl) countEl.innerText = list.length;
  9512. tbody.innerHTML = list.map(l => `
  9513. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9514. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9515. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9516. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9517. </td>
  9518. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9519. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9520. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9521. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9522. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9523. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9524. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9525. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9526. </tr>
  9527. `).join('');
  9528. }
  9529. function renderOspfStatusPill() {
  9530. // Maintained for backward compatibility
  9531. const pill = document.getElementById('ospf-live-status-pill');
  9532. if (!pill) return;
  9533. 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';
  9534. pill.innerText = 'OSPF ACTIVE';
  9535. }
  9536. function renderOspfInterfaces() {
  9537. renderOspfTemplates();
  9538. }
  9539. function renderOspfRoutes() {
  9540. // Routes retained in background
  9541. }
  9542. // BGP Modals & Actions
  9543. function openBgpInstanceModal() {
  9544. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9545. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9546. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9547. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9548. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9549. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9550. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9551. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9552. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9553. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9554. }
  9555. function closeBgpInstanceModal() {
  9556. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9557. }
  9558. async function submitBgpInstance(e) {
  9559. e.preventDefault();
  9560. const payload = {
  9561. enabled: document.getElementById('modal-bgp-enabled').checked,
  9562. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9563. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9564. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9565. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9566. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9567. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9568. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9569. };
  9570. try {
  9571. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9572. method: 'POST',
  9573. headers: { 'Content-Type': 'application/json' },
  9574. body: JSON.stringify(payload)
  9575. });
  9576. if (res.ok) {
  9577. closeBgpInstanceModal();
  9578. showToast('Success', 'BGP instance configuration updated', 'success');
  9579. loadDynamicRouting();
  9580. } else {
  9581. const err = await res.json();
  9582. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9583. }
  9584. } catch (err) {
  9585. showToast('Error', err.message, 'error');
  9586. }
  9587. }
  9588. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9589. function switchBgpPeerModalTab(tab) {
  9590. // Normalize legacy tab names
  9591. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9592. if (tab === 'attributes') tab = 'networks';
  9593. const tabs = ['general', 'filters', 'networks'];
  9594. tabs.forEach(t => {
  9595. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9596. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9597. if (t === tab) {
  9598. if (pane) pane.classList.remove('hidden');
  9599. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9600. } else {
  9601. if (pane) pane.classList.add('hidden');
  9602. 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';
  9603. }
  9604. });
  9605. }
  9606. function addOutputNetworkRow(val = '') {
  9607. const container = document.getElementById('modal-bgp-output-networks-container');
  9608. if (!container) return;
  9609. const row = document.createElement('div');
  9610. row.className = 'flex items-center gap-2 output-net-row';
  9611. row.innerHTML = `
  9612. <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">
  9613. <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>
  9614. `;
  9615. container.appendChild(row);
  9616. }
  9617. function parseBgpTime(val) {
  9618. if (!val) return 0;
  9619. val = String(val).trim();
  9620. if (val.includes(':')) {
  9621. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9622. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9623. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9624. }
  9625. return parseInt(val, 10) || 0;
  9626. }
  9627. function formatBgpTime(secs) {
  9628. if (!secs || secs <= 0) return '30';
  9629. return String(secs);
  9630. }
  9631. function populateBgpRoutingTables() {
  9632. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9633. if (!sel) return;
  9634. const cur = sel.value || 'main';
  9635. sel.innerHTML = '<option value="main">main</option>';
  9636. (state.routingTables || []).forEach(t => {
  9637. if (t.name !== 'main') {
  9638. const opt = document.createElement('option');
  9639. opt.value = t.name;
  9640. opt.innerText = t.name;
  9641. sel.appendChild(opt);
  9642. }
  9643. });
  9644. sel.value = cur;
  9645. }
  9646. function populateBgpLocalAddrDatalist() {
  9647. const dlBgp = document.getElementById('bgp-peer-local-addr-datalist');
  9648. if (!dlBgp) return;
  9649. const addrs = [];
  9650. (state.interfaces || []).forEach(iface => {
  9651. if (iface.ip) addrs.push(iface.ip.split('/')[0]);
  9652. (iface.addresses || []).forEach(a => addrs.push(a.split('/')[0]));
  9653. });
  9654. dlBgp.innerHTML = Array.from(new Set(addrs.filter(Boolean))).map(ip => `<option value="${escapeHtml(ip)}">`).join('');
  9655. }
  9656. function openAddBgpPeerModal() {
  9657. document.getElementById('bgp-peer-form').reset();
  9658. document.getElementById('modal-bgp-peer-id').value = '';
  9659. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9660. populateBgpLocalAddrDatalist();
  9661. // General Tab
  9662. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9663. document.getElementById('modal-bgp-peer-name').value = '';
  9664. document.getElementById('modal-bgp-peer-comment').value = '';
  9665. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9666. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9667. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9668. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9669. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9670. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9671. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9672. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9673. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9674. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9675. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9676. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9677. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9678. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9679. // Filters Tab
  9680. populateFilterChainsDatalist();
  9681. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9682. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9683. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9684. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9685. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9686. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9687. // Advertised Networks Tab
  9688. const container = document.getElementById('modal-bgp-output-networks-container');
  9689. if (container) {
  9690. container.innerHTML = '';
  9691. addOutputNetworkRow('');
  9692. }
  9693. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9694. if (removeBtn) removeBtn.classList.add('hidden');
  9695. switchBgpPeerModalTab('general');
  9696. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9697. }
  9698. function populateFilterChainsDatalist() {
  9699. const dl = document.getElementById('filter-chains-list');
  9700. if (!dl) return;
  9701. const chains = new Set();
  9702. (state.routingFilters || []).forEach(f => {
  9703. if (f.chain) chains.add(f.chain);
  9704. });
  9705. if (chains.size === 0) {
  9706. chains.add('awmn');
  9707. chains.add('Internal');
  9708. chains.add('bgp-in');
  9709. chains.add('bgp-out');
  9710. }
  9711. dl.innerHTML = '';
  9712. chains.forEach(c => {
  9713. const opt = document.createElement('option');
  9714. opt.value = c;
  9715. dl.appendChild(opt);
  9716. });
  9717. }
  9718. function openEditBgpPeerModal(id) {
  9719. const p = (state.bgpPeers || []).find(item => item.id === id);
  9720. if (!p) return;
  9721. populateFilterChainsDatalist();
  9722. populateBgpLocalAddrDatalist();
  9723. document.getElementById('modal-bgp-peer-id').value = p.id;
  9724. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9725. // General Tab
  9726. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9727. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9728. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9729. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9730. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9731. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9732. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9733. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9734. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9735. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9736. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9737. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9738. // Passive mode
  9739. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9740. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9741. // Next-hop self
  9742. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9743. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9744. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9745. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9746. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9747. // Filters Tab
  9748. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9749. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9750. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9751. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9752. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9753. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9754. // Advertised Networks Tab
  9755. const container = document.getElementById('modal-bgp-output-networks-container');
  9756. if (container) {
  9757. container.innerHTML = '';
  9758. if (p.output_networks && p.output_networks.length > 0) {
  9759. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9760. } else {
  9761. addOutputNetworkRow('');
  9762. }
  9763. }
  9764. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9765. if (removeBtn) removeBtn.classList.remove('hidden');
  9766. switchBgpPeerModalTab('general');
  9767. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9768. }
  9769. function copyCurrentBgpPeer() {
  9770. document.getElementById('modal-bgp-peer-id').value = '';
  9771. const nameEl = document.getElementById('modal-bgp-peer-name');
  9772. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9773. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9774. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9775. if (removeBtn) removeBtn.classList.add('hidden');
  9776. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9777. }
  9778. function removeCurrentBgpPeer() {
  9779. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9780. if (!id) return;
  9781. deleteBgpPeer(id);
  9782. closeBgpPeerModal();
  9783. }
  9784. function closeBgpPeerModal() {
  9785. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9786. }
  9787. function getBgpPeerFormData() {
  9788. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9789. const outputNetworks = [];
  9790. netInputs.forEach(inp => {
  9791. const v = inp.value.trim();
  9792. if (v) outputNetworks.push(v);
  9793. });
  9794. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9795. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9796. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9797. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9798. return {
  9799. id: document.getElementById('modal-bgp-peer-id').value,
  9800. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9801. enabled: enabled,
  9802. disabled: !enabled,
  9803. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9804. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9805. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9806. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9807. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9808. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9809. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9810. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9811. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9812. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9813. use_bfd: useBfd,
  9814. passive: isPassive,
  9815. connect: !isPassive,
  9816. listen: true,
  9817. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9818. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9819. nexthop_self: isNexthopSelf,
  9820. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9821. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9822. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9823. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9824. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9825. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9826. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9827. output_networks: outputNetworks
  9828. };
  9829. }
  9830. async function submitBgpPeer(e) {
  9831. if (e) e.preventDefault();
  9832. const payload = getBgpPeerFormData();
  9833. try {
  9834. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9835. method: 'POST',
  9836. headers: { 'Content-Type': 'application/json' },
  9837. body: JSON.stringify(payload)
  9838. });
  9839. if (res.ok) {
  9840. closeBgpPeerModal();
  9841. showToast('Success', 'BGP Connection saved', 'success');
  9842. loadDynamicRouting();
  9843. } else {
  9844. const err = await res.json();
  9845. showToast('Error', err.error || 'Failed to save peer', 'error');
  9846. }
  9847. } catch (err) {
  9848. showToast('Error', err.message, 'error');
  9849. }
  9850. }
  9851. async function applyBgpPeerModal(e) {
  9852. if (e) e.preventDefault();
  9853. const payload = getBgpPeerFormData();
  9854. try {
  9855. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9856. method: 'POST',
  9857. headers: { 'Content-Type': 'application/json' },
  9858. body: JSON.stringify(payload)
  9859. });
  9860. if (res.ok) {
  9861. const data = await res.json();
  9862. if (data.peer && data.peer.id) {
  9863. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9864. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9865. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9866. }
  9867. showToast('Applied', 'BGP Connection applied', 'success');
  9868. loadDynamicRouting();
  9869. } else {
  9870. const err = await res.json();
  9871. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9872. }
  9873. } catch (err) {
  9874. showToast('Error', err.message, 'error');
  9875. }
  9876. }
  9877. async function deleteBgpPeer(id) {
  9878. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9879. try {
  9880. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9881. if (res.ok) {
  9882. showToast('Deleted', 'BGP peer removed', 'success');
  9883. loadDynamicRouting();
  9884. }
  9885. } catch (err) {
  9886. showToast('Error', err.message, 'error');
  9887. }
  9888. }
  9889. async function toggleBgpPeerState(id, disabled) {
  9890. try {
  9891. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9892. method: 'POST',
  9893. headers: { 'Content-Type': 'application/json' },
  9894. body: JSON.stringify({ disabled })
  9895. });
  9896. if (res.ok) {
  9897. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9898. loadDynamicRouting();
  9899. }
  9900. } catch (err) {
  9901. showToast('Error', err.message, 'error');
  9902. }
  9903. }
  9904. function openAddBgpNetworkModal() {
  9905. document.getElementById('bgp-network-form').reset();
  9906. document.getElementById('modal-bgp-net-id').value = '';
  9907. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9908. }
  9909. function closeBgpNetworkModal() {
  9910. document.getElementById('bgp-network-modal').classList.add('hidden');
  9911. }
  9912. async function submitBgpNetwork(e) {
  9913. e.preventDefault();
  9914. const payload = {
  9915. id: document.getElementById('modal-bgp-net-id').value,
  9916. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9917. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9918. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9919. };
  9920. try {
  9921. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9922. method: 'POST',
  9923. headers: { 'Content-Type': 'application/json' },
  9924. body: JSON.stringify(payload)
  9925. });
  9926. if (res.ok) {
  9927. closeBgpNetworkModal();
  9928. showToast('Success', 'BGP network advertisement saved', 'success');
  9929. loadDynamicRouting();
  9930. } else {
  9931. const err = await res.json();
  9932. showToast('Error', err.error || 'Failed to save network', 'error');
  9933. }
  9934. } catch (err) {
  9935. showToast('Error', err.message, 'error');
  9936. }
  9937. }
  9938. async function deleteBgpNetwork(id) {
  9939. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9940. try {
  9941. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9942. if (res.ok) {
  9943. showToast('Deleted', 'Network advertisement removed', 'success');
  9944. loadDynamicRouting();
  9945. }
  9946. } catch (err) {
  9947. showToast('Error', err.message, 'error');
  9948. }
  9949. }
  9950. // =========================================================================
  9951. // DEBTIK v7 OSPF MODALS & ACTIONS
  9952. // =========================================================================
  9953. // --- 1. OSPF INSTANCE ---
  9954. function openOspfInstanceModal(id = null) {
  9955. const isEdit = !!id;
  9956. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9957. id: '',
  9958. name: 'Default',
  9959. version: 2,
  9960. vrf: 'main',
  9961. router_id: '192.168.131.56',
  9962. routing_table: 'main',
  9963. enabled: true,
  9964. redistribute_connected: false,
  9965. redistribute_static: true,
  9966. redistribute_bgp: false,
  9967. comment: ''
  9968. };
  9969. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9970. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9971. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9972. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9973. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9974. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9975. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9976. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9977. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9978. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9979. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9980. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9981. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  9982. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9983. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  9984. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  9985. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  9986. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9987. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9988. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9989. }
  9990. function toggleOspfDefaultModeUI() {
  9991. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  9992. const select = document.getElementById('modal-ospf-inst-originate-default');
  9993. if (!select) return;
  9994. if (isChecked) {
  9995. if (select.value === 'never') select.value = 'if-installed';
  9996. } else {
  9997. select.value = 'never';
  9998. }
  9999. }
  10000. function onOspfOriginateDefaultChange() {
  10001. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  10002. const chk = document.getElementById('modal-ospf-inst-redist-default');
  10003. if (chk) chk.checked = val !== 'never';
  10004. }
  10005. function openEditOspfInstanceModal(id) {
  10006. openOspfInstanceModal(id);
  10007. }
  10008. function closeOspfInstanceModal() {
  10009. document.getElementById('ospf-instance-modal').classList.add('hidden');
  10010. }
  10011. async function submitOspfInstance(e) {
  10012. if (e) e.preventDefault();
  10013. const payload = {
  10014. id: document.getElementById('modal-ospf-inst-id').value,
  10015. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10016. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10017. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10018. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10019. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10020. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10021. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10022. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10023. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10024. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10025. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10026. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10027. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10028. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  10029. };
  10030. try {
  10031. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10032. method: 'POST',
  10033. headers: { 'Content-Type': 'application/json' },
  10034. body: JSON.stringify(payload)
  10035. });
  10036. if (res.ok) {
  10037. closeOspfInstanceModal();
  10038. showToast('Saved', 'OSPF instance updated', 'success');
  10039. loadDynamicRouting();
  10040. } else {
  10041. const err = await res.json();
  10042. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10043. }
  10044. } catch (err) {
  10045. showToast('Error', err.message, 'error');
  10046. }
  10047. }
  10048. function applyOspfInstanceForm() {
  10049. submitOspfInstance(null);
  10050. }
  10051. function copyOspfInstance() {
  10052. document.getElementById('modal-ospf-inst-id').value = '';
  10053. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10054. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10055. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10056. }
  10057. async function deleteCurrentOspfInstance() {
  10058. const id = document.getElementById('modal-ospf-inst-id').value;
  10059. if (!id) return;
  10060. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10061. try {
  10062. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10063. if (res.ok) {
  10064. closeOspfInstanceModal();
  10065. showToast('Removed', 'OSPF instance deleted', 'success');
  10066. loadDynamicRouting();
  10067. }
  10068. } catch (err) {
  10069. showToast('Error', err.message, 'error');
  10070. }
  10071. }
  10072. async function enableSelectedOspfInstance() {
  10073. const id = state.selectedOspfRow?.instances;
  10074. if (!id) return;
  10075. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10076. method: 'POST',
  10077. headers: { 'Content-Type': 'application/json' },
  10078. body: JSON.stringify({ disabled: false })
  10079. });
  10080. loadDynamicRouting();
  10081. }
  10082. async function disableSelectedOspfInstance() {
  10083. const id = state.selectedOspfRow?.instances;
  10084. if (!id) return;
  10085. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10086. method: 'POST',
  10087. headers: { 'Content-Type': 'application/json' },
  10088. body: JSON.stringify({ disabled: true })
  10089. });
  10090. loadDynamicRouting();
  10091. }
  10092. async function removeSelectedOspfInstance() {
  10093. const id = state.selectedOspfRow?.instances;
  10094. if (!id) return;
  10095. if (!confirm('Delete selected OSPF instance?')) return;
  10096. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10097. loadDynamicRouting();
  10098. }
  10099. async function promptCommentOspfInstance() {
  10100. const id = state.selectedOspfRow?.instances;
  10101. if (!id) return;
  10102. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10103. if (!inst) return;
  10104. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10105. if (comment === null) return;
  10106. inst.comment = comment;
  10107. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10108. method: 'POST',
  10109. headers: { 'Content-Type': 'application/json' },
  10110. body: JSON.stringify(inst)
  10111. });
  10112. loadDynamicRouting();
  10113. }
  10114. // --- 2. OSPF AREA ---
  10115. function populateOspfAreaDropdowns() {
  10116. const instSelect = document.getElementById('modal-ospf-area-instance');
  10117. if (instSelect) {
  10118. const cur = instSelect.value;
  10119. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10120. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10121. if (cur) instSelect.value = cur;
  10122. }
  10123. }
  10124. function openOspfAreaModal(id = null) {
  10125. const isEdit = !!id;
  10126. populateOspfAreaDropdowns();
  10127. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10128. id: '',
  10129. name: 'Default',
  10130. instance: 'Default',
  10131. area_id: '0.0.0.0',
  10132. area_type: 'default',
  10133. default_cost: 1,
  10134. no_summaries: false,
  10135. disabled: false,
  10136. comment: ''
  10137. };
  10138. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10139. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10140. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10141. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10142. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10143. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10144. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10145. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10146. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10147. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10148. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10149. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10150. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10151. }
  10152. function openEditOspfAreaModal(id) {
  10153. openOspfAreaModal(id);
  10154. }
  10155. function closeOspfAreaModal() {
  10156. document.getElementById('ospf-area-modal').classList.add('hidden');
  10157. }
  10158. async function submitOspfArea(e) {
  10159. if (e) e.preventDefault();
  10160. const payload = {
  10161. id: document.getElementById('modal-ospf-area-id').value,
  10162. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10163. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10164. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10165. area_type: document.getElementById('modal-ospf-area-type').value,
  10166. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10167. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10168. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10169. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10170. };
  10171. try {
  10172. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10173. method: 'POST',
  10174. headers: { 'Content-Type': 'application/json' },
  10175. body: JSON.stringify(payload)
  10176. });
  10177. if (res.ok) {
  10178. closeOspfAreaModal();
  10179. showToast('Saved', 'OSPF area saved', 'success');
  10180. loadDynamicRouting();
  10181. } else {
  10182. const err = await res.json();
  10183. showToast('Error', err.error || 'Failed to save area', 'error');
  10184. }
  10185. } catch (err) {
  10186. showToast('Error', err.message, 'error');
  10187. }
  10188. }
  10189. function applyOspfAreaForm() {
  10190. submitOspfArea(null);
  10191. }
  10192. function copyOspfArea() {
  10193. document.getElementById('modal-ospf-area-id').value = '';
  10194. document.getElementById('modal-ospf-area-name').value += '-copy';
  10195. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10196. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10197. }
  10198. async function deleteCurrentOspfArea() {
  10199. const id = document.getElementById('modal-ospf-area-id').value;
  10200. if (!id) return;
  10201. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10202. try {
  10203. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10204. if (res.ok) {
  10205. closeOspfAreaModal();
  10206. showToast('Removed', 'OSPF area deleted', 'success');
  10207. loadDynamicRouting();
  10208. }
  10209. } catch (err) {
  10210. showToast('Error', err.message, 'error');
  10211. }
  10212. }
  10213. async function enableSelectedOspfArea() {
  10214. const id = state.selectedOspfRow?.areas;
  10215. if (!id) return;
  10216. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10217. method: 'POST',
  10218. headers: { 'Content-Type': 'application/json' },
  10219. body: JSON.stringify({ disabled: false })
  10220. });
  10221. loadDynamicRouting();
  10222. }
  10223. async function disableSelectedOspfArea() {
  10224. const id = state.selectedOspfRow?.areas;
  10225. if (!id) return;
  10226. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10227. method: 'POST',
  10228. headers: { 'Content-Type': 'application/json' },
  10229. body: JSON.stringify({ disabled: true })
  10230. });
  10231. loadDynamicRouting();
  10232. }
  10233. async function removeSelectedOspfArea() {
  10234. const id = state.selectedOspfRow?.areas;
  10235. if (!id) return;
  10236. if (!confirm('Delete selected OSPF area?')) return;
  10237. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10238. loadDynamicRouting();
  10239. }
  10240. async function promptCommentOspfArea() {
  10241. const id = state.selectedOspfRow?.areas;
  10242. if (!id) return;
  10243. const area = (state.ospfAreas || []).find(a => a.id === id);
  10244. if (!area) return;
  10245. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10246. if (comment === null) return;
  10247. area.comment = comment;
  10248. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10249. method: 'POST',
  10250. headers: { 'Content-Type': 'application/json' },
  10251. body: JSON.stringify(area)
  10252. });
  10253. loadDynamicRouting();
  10254. }
  10255. // --- 3. OSPF AREA RANGE ---
  10256. function populateAreaRangeDropdowns() {
  10257. const select = document.getElementById('modal-ospf-range-area');
  10258. if (select) {
  10259. const cur = select.value;
  10260. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10261. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10262. if (cur) select.value = cur;
  10263. }
  10264. }
  10265. function openOspfAreaRangeModal(id = null) {
  10266. const isEdit = !!id;
  10267. populateAreaRangeDropdowns();
  10268. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10269. id: '',
  10270. area: 'Default',
  10271. prefix: '',
  10272. cost: 1,
  10273. advertise: true,
  10274. disabled: false,
  10275. comment: ''
  10276. };
  10277. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10278. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10279. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10280. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10281. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10282. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10283. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10284. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10285. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10286. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10287. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10288. }
  10289. function openEditOspfAreaRangeModal(id) {
  10290. openOspfAreaRangeModal(id);
  10291. }
  10292. function closeOspfAreaRangeModal() {
  10293. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10294. }
  10295. async function submitOspfAreaRange(e) {
  10296. if (e) e.preventDefault();
  10297. const payload = {
  10298. id: document.getElementById('modal-ospf-range-id').value,
  10299. area: document.getElementById('modal-ospf-range-area').value,
  10300. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10301. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10302. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10303. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10304. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10305. };
  10306. try {
  10307. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10308. method: 'POST',
  10309. headers: { 'Content-Type': 'application/json' },
  10310. body: JSON.stringify(payload)
  10311. });
  10312. if (res.ok) {
  10313. closeOspfAreaRangeModal();
  10314. showToast('Saved', 'Area range saved', 'success');
  10315. loadDynamicRouting();
  10316. } else {
  10317. const err = await res.json();
  10318. showToast('Error', err.error || 'Failed to save area range', 'error');
  10319. }
  10320. } catch (err) {
  10321. showToast('Error', err.message, 'error');
  10322. }
  10323. }
  10324. function applyOspfAreaRangeForm() {
  10325. submitOspfAreaRange(null);
  10326. }
  10327. async function deleteCurrentOspfAreaRange() {
  10328. const id = document.getElementById('modal-ospf-range-id').value;
  10329. if (!id) return;
  10330. if (!confirm('Delete this area range?')) return;
  10331. try {
  10332. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10333. closeOspfAreaRangeModal();
  10334. showToast('Removed', 'Area range removed', 'success');
  10335. loadDynamicRouting();
  10336. } catch (err) {
  10337. showToast('Error', err.message, 'error');
  10338. }
  10339. }
  10340. async function enableSelectedOspfAreaRange() {
  10341. const id = state.selectedOspfRow?.['area-ranges'];
  10342. if (!id) return;
  10343. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10344. if (!r) return;
  10345. r.disabled = false;
  10346. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10347. loadDynamicRouting();
  10348. }
  10349. async function disableSelectedOspfAreaRange() {
  10350. const id = state.selectedOspfRow?.['area-ranges'];
  10351. if (!id) return;
  10352. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10353. if (!r) return;
  10354. r.disabled = true;
  10355. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10356. loadDynamicRouting();
  10357. }
  10358. async function removeSelectedOspfAreaRange() {
  10359. const id = state.selectedOspfRow?.['area-ranges'];
  10360. if (!id) return;
  10361. if (!confirm('Delete selected area range?')) return;
  10362. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10363. loadDynamicRouting();
  10364. }
  10365. async function promptCommentOspfAreaRange() {
  10366. const id = state.selectedOspfRow?.['area-ranges'];
  10367. if (!id) return;
  10368. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10369. if (!r) return;
  10370. const comment = prompt('Enter comment for area range:', r.comment || '');
  10371. if (comment === null) return;
  10372. r.comment = comment;
  10373. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10374. loadDynamicRouting();
  10375. }
  10376. // --- 4. OSPF INTERFACE TEMPLATE ---
  10377. function switchOspfTemplateTab(tab) {
  10378. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10379. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10380. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10381. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10382. if (tab === 'general') {
  10383. if (tabGen) tabGen.classList.remove('hidden');
  10384. if (tabAuth) tabAuth.classList.add('hidden');
  10385. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10386. 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';
  10387. } else {
  10388. if (tabGen) tabGen.classList.add('hidden');
  10389. if (tabAuth) tabAuth.classList.remove('hidden');
  10390. 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';
  10391. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10392. }
  10393. }
  10394. function populateTemplateAreaDropdowns() {
  10395. const select = document.getElementById('modal-ospf-tmpl-area');
  10396. if (select) {
  10397. const cur = select.value;
  10398. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10399. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10400. if (cur) select.value = cur;
  10401. }
  10402. }
  10403. function openOspfTemplateModal(id = null) {
  10404. const isEdit = !!id;
  10405. populateTemplateAreaDropdowns();
  10406. switchOspfTemplateTab('general');
  10407. const dl = document.getElementById('ospf-tmpl-iface-datalist');
  10408. if (dl) {
  10409. dl.innerHTML = '<option value="*"><option value="all">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  10410. }
  10411. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10412. id: '',
  10413. interfaces: '',
  10414. area: 'Default',
  10415. networks: '',
  10416. network_type: 'broadcast',
  10417. cost: 1,
  10418. priority: 128,
  10419. passive: false,
  10420. hello_interval: 10,
  10421. dead_interval: 40,
  10422. auth: 'none',
  10423. auth_key: '',
  10424. disabled: false,
  10425. comment: ''
  10426. };
  10427. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10428. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10429. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10430. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10431. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10432. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10433. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10434. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10435. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10436. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10437. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10438. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10439. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10440. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10441. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10442. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10443. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10444. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10445. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10446. }
  10447. function openEditOspfTemplateModal(id) {
  10448. openOspfTemplateModal(id);
  10449. }
  10450. function closeOspfTemplateModal() {
  10451. document.getElementById('ospf-template-modal').classList.add('hidden');
  10452. }
  10453. async function submitOspfTemplate(e) {
  10454. if (e) e.preventDefault();
  10455. const payload = {
  10456. id: document.getElementById('modal-ospf-tmpl-id').value,
  10457. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10458. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10459. area: document.getElementById('modal-ospf-tmpl-area').value,
  10460. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10461. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10462. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10463. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10464. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10465. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10466. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10467. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10468. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10469. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10470. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10471. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10472. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10473. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10474. };
  10475. try {
  10476. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10477. method: 'POST',
  10478. headers: { 'Content-Type': 'application/json' },
  10479. body: JSON.stringify(payload)
  10480. });
  10481. if (res.ok) {
  10482. closeOspfTemplateModal();
  10483. showToast('Saved', 'Interface template saved', 'success');
  10484. loadDynamicRouting();
  10485. } else {
  10486. const err = await res.json();
  10487. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10488. }
  10489. } catch (err) {
  10490. showToast('Error', err.message, 'error');
  10491. }
  10492. }
  10493. function applyOspfTemplateForm() {
  10494. submitOspfTemplate(null);
  10495. }
  10496. function copyOspfTemplate() {
  10497. document.getElementById('modal-ospf-tmpl-id').value = '';
  10498. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10499. showToast('Copied', 'Duplicated as new template', 'info');
  10500. }
  10501. async function deleteCurrentOspfTemplate() {
  10502. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10503. if (!id) return;
  10504. if (!confirm('Delete this interface template?')) return;
  10505. try {
  10506. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10507. closeOspfTemplateModal();
  10508. showToast('Removed', 'Interface template deleted', 'success');
  10509. loadDynamicRouting();
  10510. } catch (err) {
  10511. showToast('Error', err.message, 'error');
  10512. }
  10513. }
  10514. async function enableSelectedOspfTemplate() {
  10515. const id = state.selectedOspfRow?.templates;
  10516. if (!id) return;
  10517. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10518. method: 'POST',
  10519. headers: { 'Content-Type': 'application/json' },
  10520. body: JSON.stringify({ disabled: false })
  10521. });
  10522. loadDynamicRouting();
  10523. }
  10524. async function disableSelectedOspfTemplate() {
  10525. const id = state.selectedOspfRow?.templates;
  10526. if (!id) return;
  10527. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10528. method: 'POST',
  10529. headers: { 'Content-Type': 'application/json' },
  10530. body: JSON.stringify({ disabled: true })
  10531. });
  10532. loadDynamicRouting();
  10533. }
  10534. async function removeSelectedOspfTemplate() {
  10535. const id = state.selectedOspfRow?.templates;
  10536. if (!id) return;
  10537. if (!confirm('Delete selected interface template?')) return;
  10538. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10539. loadDynamicRouting();
  10540. }
  10541. async function promptCommentOspfTemplate() {
  10542. const id = state.selectedOspfRow?.templates;
  10543. if (!id) return;
  10544. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10545. if (!tmpl) return;
  10546. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10547. if (comment === null) return;
  10548. tmpl.comment = comment;
  10549. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10550. method: 'POST',
  10551. headers: { 'Content-Type': 'application/json' },
  10552. body: JSON.stringify(tmpl)
  10553. });
  10554. loadDynamicRouting();
  10555. }
  10556. // --- 5. OSPF STATIC NEIGHBOR ---
  10557. function populateStaticNbrAreaDropdowns() {
  10558. const select = document.getElementById('modal-ospf-snbr-area');
  10559. if (select) {
  10560. const cur = select.value;
  10561. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10562. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10563. if (cur) select.value = cur;
  10564. }
  10565. }
  10566. function openOspfStaticNbrModal(id = null) {
  10567. const isEdit = !!id;
  10568. populateStaticNbrAreaDropdowns();
  10569. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10570. id: '',
  10571. address: '',
  10572. area: 'Default',
  10573. poll_interval: 120,
  10574. cost: 1,
  10575. disabled: false,
  10576. comment: ''
  10577. };
  10578. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10579. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10580. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10581. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10582. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10583. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10584. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10585. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10586. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10587. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10588. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10589. }
  10590. function openEditOspfStaticNbrModal(id) {
  10591. openOspfStaticNbrModal(id);
  10592. }
  10593. function closeOspfStaticNbrModal() {
  10594. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10595. }
  10596. async function submitOspfStaticNbr(e) {
  10597. if (e) e.preventDefault();
  10598. const payload = {
  10599. id: document.getElementById('modal-ospf-snbr-id').value,
  10600. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10601. area: document.getElementById('modal-ospf-snbr-area').value,
  10602. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10603. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10604. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10605. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10606. };
  10607. try {
  10608. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10609. method: 'POST',
  10610. headers: { 'Content-Type': 'application/json' },
  10611. body: JSON.stringify(payload)
  10612. });
  10613. if (res.ok) {
  10614. closeOspfStaticNbrModal();
  10615. showToast('Saved', 'Static neighbor saved', 'success');
  10616. loadDynamicRouting();
  10617. } else {
  10618. const err = await res.json();
  10619. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10620. }
  10621. } catch (err) {
  10622. showToast('Error', err.message, 'error');
  10623. }
  10624. }
  10625. function applyOspfStaticNbrForm() {
  10626. submitOspfStaticNbr(null);
  10627. }
  10628. async function deleteCurrentOspfStaticNbr() {
  10629. const id = document.getElementById('modal-ospf-snbr-id').value;
  10630. if (!id) return;
  10631. if (!confirm('Delete this static neighbor?')) return;
  10632. try {
  10633. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10634. closeOspfStaticNbrModal();
  10635. showToast('Removed', 'Static neighbor removed', 'success');
  10636. loadDynamicRouting();
  10637. } catch (err) {
  10638. showToast('Error', err.message, 'error');
  10639. }
  10640. }
  10641. async function enableSelectedOspfStaticNbr() {
  10642. const id = state.selectedOspfRow?.['static-nbrs'];
  10643. if (!id) return;
  10644. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10645. loadDynamicRouting();
  10646. }
  10647. async function disableSelectedOspfStaticNbr() {
  10648. const id = state.selectedOspfRow?.['static-nbrs'];
  10649. if (!id) return;
  10650. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10651. loadDynamicRouting();
  10652. }
  10653. async function removeSelectedOspfStaticNbr() {
  10654. const id = state.selectedOspfRow?.['static-nbrs'];
  10655. if (!id) return;
  10656. if (!confirm('Delete selected static neighbor?')) return;
  10657. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10658. loadDynamicRouting();
  10659. }
  10660. async function promptCommentOspfStaticNbr() {
  10661. const id = state.selectedOspfRow?.['static-nbrs'];
  10662. if (!id) return;
  10663. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10664. if (!n) return;
  10665. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10666. if (comment === null) return;
  10667. n.comment = comment;
  10668. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10669. loadDynamicRouting();
  10670. }
  10671. // Backward-compat aliases
  10672. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10673. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10674. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10675. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10676. function deleteOspfInterface(id) {
  10677. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10678. }
  10679. function toggleOspfInterfaceState(id, disabled) {
  10680. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10681. method: 'POST',
  10682. headers: { 'Content-Type': 'application/json' },
  10683. body: JSON.stringify({ disabled })
  10684. }).then(() => loadDynamicRouting());
  10685. }
  10686. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10687. function deleteOspfArea(id) {
  10688. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10689. }
  10690. // ============================================================================
  10691. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10692. // ============================================================================
  10693. function switchBridgeSubTab(tab) {
  10694. state.bridgeSubTab = tab;
  10695. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10696. tabs.forEach(t => {
  10697. const panel = document.getElementById(`bridge-subtab-${t}`);
  10698. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10699. if (panel) {
  10700. if (t === tab) panel.classList.remove('hidden');
  10701. else panel.classList.add('hidden');
  10702. }
  10703. if (btn) {
  10704. if (t === tab) {
  10705. 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';
  10706. } else {
  10707. 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';
  10708. }
  10709. }
  10710. });
  10711. const addBtn = document.getElementById('bridge-top-action-btn');
  10712. if (addBtn) {
  10713. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10714. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10715. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10716. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10717. }
  10718. if (tab === 'hosts') loadBridgeHosts();
  10719. setTimeout(initTableSorting, 50);
  10720. }
  10721. function openCurrentBridgeModal() {
  10722. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10723. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10724. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10725. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10726. }
  10727. async function loadBridge() {
  10728. try {
  10729. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10730. fetch(`${API_BASE}/bridge/bridges`),
  10731. fetch(`${API_BASE}/bridge/ports`),
  10732. fetch(`${API_BASE}/bridge/vlans`),
  10733. fetch(`${API_BASE}/bridge/summary`),
  10734. fetch(`${API_BASE}/vpn/eoip`),
  10735. fetch(`${API_BASE}/vpn/vxlan`),
  10736. fetch(`${API_BASE}/vlans`)
  10737. ]);
  10738. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10739. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10740. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10741. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10742. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10743. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10744. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10745. // Badges & Stats
  10746. const bBridges = document.getElementById('bridge-badge-bridges');
  10747. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10748. const bPorts = document.getElementById('bridge-badge-ports');
  10749. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10750. const bVlans = document.getElementById('bridge-badge-vlans');
  10751. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10752. const bHosts = document.getElementById('bridge-badge-hosts');
  10753. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10754. const sBr = document.getElementById('bridge-stat-bridges');
  10755. if (sBr) sBr.innerText = (state.bridges || []).length;
  10756. const sPorts = document.getElementById('bridge-stat-ports');
  10757. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10758. const sHosts = document.getElementById('bridge-stat-hosts');
  10759. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10760. renderBridges();
  10761. renderBridgePorts();
  10762. renderBridgeVLANs();
  10763. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10764. } catch (err) {
  10765. console.error('Failed to load bridge subsystem:', err);
  10766. }
  10767. }
  10768. // ----------------- Bridges -----------------
  10769. function renderBridges() {
  10770. const tbody = document.getElementById('bridge-table-body');
  10771. const empty = document.getElementById('bridge-empty-bridges');
  10772. const countBadge = document.getElementById('bridge-count-badge');
  10773. if (!tbody) return;
  10774. tbody.innerHTML = '';
  10775. const bridges = state.bridges || [];
  10776. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10777. if (bridges.length === 0) {
  10778. empty?.classList.remove('hidden');
  10779. return;
  10780. }
  10781. empty?.classList.add('hidden');
  10782. bridges.forEach((b, idx) => {
  10783. const tr = document.createElement('tr');
  10784. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10785. // Format IP addresses pill list
  10786. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10787. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10788. ipsHtml = b.ip_addresses.map(ip => `
  10789. <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">
  10790. <span>${ip}</span>
  10791. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10792. </span>
  10793. `).join(' ');
  10794. }
  10795. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10796. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10797. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10798. tr.innerHTML = `
  10799. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10800. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10801. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10802. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10803. </td>
  10804. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10805. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10806. <td class="py-2.5 px-3">
  10807. <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>
  10808. </td>
  10809. <td class="py-2.5 px-3 text-center">
  10810. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10811. </td>
  10812. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10813. <td class="py-2.5 px-3">
  10814. <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>
  10815. </td>
  10816. <td class="py-2.5 px-3">
  10817. <div class="flex items-center gap-1.5 flex-wrap">
  10818. ${ipsHtml}
  10819. <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>
  10820. </div>
  10821. </td>
  10822. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10823. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10824. </td>
  10825. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10826. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10827. <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>
  10828. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10829. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10830. </td>
  10831. `;
  10832. tbody.appendChild(tr);
  10833. });
  10834. }
  10835. function openAddBridgeModal() {
  10836. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10837. document.getElementById('bridge-modal-id').value = '';
  10838. document.getElementById('bridge-modal-name').value = 'bridge1';
  10839. document.getElementById('bridge-modal-name').disabled = false;
  10840. document.getElementById('bridge-modal-mtu').value = '1500';
  10841. document.getElementById('bridge-modal-mac').value = '';
  10842. document.getElementById('bridge-modal-stp').value = 'stp';
  10843. document.getElementById('bridge-modal-priority').value = '32768';
  10844. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10845. document.getElementById('bridge-modal-pvid').value = '1';
  10846. document.getElementById('bridge-modal-fastforward').checked = true;
  10847. document.getElementById('bridge-modal-comment').value = '';
  10848. document.getElementById('bridge-modal-disabled').checked = false;
  10849. toggleBridgeModalVlanFiltering();
  10850. document.getElementById('bridge-modal').classList.remove('hidden');
  10851. }
  10852. function openEditBridgeModal(id) {
  10853. const b = (state.bridges || []).find(x => x.id === id);
  10854. if (!b) return;
  10855. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10856. document.getElementById('bridge-modal-id').value = b.id;
  10857. document.getElementById('bridge-modal-name').value = b.name;
  10858. document.getElementById('bridge-modal-name').disabled = true;
  10859. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10860. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10861. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10862. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10863. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10864. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10865. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10866. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10867. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10868. toggleBridgeModalVlanFiltering();
  10869. document.getElementById('bridge-modal').classList.remove('hidden');
  10870. }
  10871. function closeBridgeModal() {
  10872. document.getElementById('bridge-modal').classList.add('hidden');
  10873. }
  10874. function toggleBridgeModalVlanFiltering() {
  10875. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10876. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10877. if (pvidBox) {
  10878. if (chk) pvidBox.classList.remove('opacity-40');
  10879. else pvidBox.classList.add('opacity-40');
  10880. }
  10881. }
  10882. async function submitSaveBridge(e) {
  10883. e.preventDefault();
  10884. const id = document.getElementById('bridge-modal-id').value;
  10885. const name = document.getElementById('bridge-modal-name').value.trim();
  10886. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10887. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10888. const stp = document.getElementById('bridge-modal-stp').value;
  10889. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10890. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10891. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10892. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10893. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10894. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10895. try {
  10896. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10897. method: 'POST',
  10898. headers: { 'Content-Type': 'application/json' },
  10899. body: JSON.stringify({
  10900. id,
  10901. name,
  10902. mtu,
  10903. mac_address: mac,
  10904. stp,
  10905. priority,
  10906. vlan_filtering: vlanFiltering,
  10907. pvid,
  10908. fast_forward: fastForward,
  10909. comment,
  10910. disabled
  10911. })
  10912. });
  10913. if (res.ok) {
  10914. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10915. closeBridgeModal();
  10916. loadBridge();
  10917. fetchData(false);
  10918. } else {
  10919. const err = await res.json();
  10920. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10921. }
  10922. } catch (err) {
  10923. showToast('Error', err.message, 'error');
  10924. }
  10925. }
  10926. async function toggleBridgeState(id, disabled) {
  10927. try {
  10928. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10929. method: 'POST',
  10930. headers: { 'Content-Type': 'application/json' },
  10931. body: JSON.stringify({ disabled })
  10932. });
  10933. if (res.ok) {
  10934. loadBridge();
  10935. fetchData(false);
  10936. }
  10937. } catch (err) {
  10938. showToast('Error', err.message, 'error');
  10939. }
  10940. }
  10941. async function deleteBridge(id) {
  10942. const b = (state.bridges || []).find(x => x.id === id);
  10943. const name = b ? b.name : id;
  10944. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10945. try {
  10946. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10947. if (res.ok) {
  10948. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10949. loadBridge();
  10950. fetchData(false);
  10951. } else {
  10952. const err = await res.json();
  10953. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10954. }
  10955. } catch (err) {
  10956. showToast('Error', err.message, 'error');
  10957. }
  10958. }
  10959. // ----------------- Bridge IP Assignments -----------------
  10960. function openAddBridgeIPModal(id, name) {
  10961. document.getElementById('bridge-ip-modal-id').value = id;
  10962. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10963. document.getElementById('bridge-ip-modal-cidr').value = '';
  10964. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10965. }
  10966. function closeBridgeIPModal() {
  10967. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10968. }
  10969. async function submitAddBridgeIP(e) {
  10970. e.preventDefault();
  10971. const id = document.getElementById('bridge-ip-modal-id').value;
  10972. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10973. try {
  10974. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10975. method: 'POST',
  10976. headers: { 'Content-Type': 'application/json' },
  10977. body: JSON.stringify({ ip })
  10978. });
  10979. if (res.ok) {
  10980. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10981. closeBridgeIPModal();
  10982. loadBridge();
  10983. fetchData(false);
  10984. } else {
  10985. const err = await res.json();
  10986. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10987. }
  10988. } catch (err) {
  10989. showToast('Error', err.message, 'error');
  10990. }
  10991. }
  10992. async function deleteBridgeIP(id, ip) {
  10993. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10994. try {
  10995. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10996. method: 'DELETE',
  10997. headers: { 'Content-Type': 'application/json' },
  10998. body: JSON.stringify({ ip })
  10999. });
  11000. if (res.ok) {
  11001. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  11002. loadBridge();
  11003. fetchData(false);
  11004. }
  11005. } catch (err) {
  11006. showToast('Error', err.message, 'error');
  11007. }
  11008. }
  11009. // ----------------- Bridge Ports -----------------
  11010. function renderBridgePorts() {
  11011. const tbody = document.getElementById('bridge-ports-table-body');
  11012. const empty = document.getElementById('bridge-empty-ports');
  11013. const countBadge = document.getElementById('bridge-ports-count-badge');
  11014. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  11015. if (!tbody) return;
  11016. tbody.innerHTML = '';
  11017. // Update filter select
  11018. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  11019. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11020. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11021. if (ports.length === 0) {
  11022. empty?.classList.remove('hidden');
  11023. return;
  11024. }
  11025. empty?.classList.add('hidden');
  11026. ports.forEach((p, idx) => {
  11027. const tr = document.createElement('tr');
  11028. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11029. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11030. tr.innerHTML = `
  11031. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11032. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11033. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11034. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11035. </td>
  11036. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11037. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11038. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11039. <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>
  11040. <td class="py-2.5 px-3">
  11041. ${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>'}
  11042. </td>
  11043. <td class="py-2.5 px-3">
  11044. <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>
  11045. </td>
  11046. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11047. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11048. <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>
  11049. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11050. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11051. </td>
  11052. `;
  11053. tbody.appendChild(tr);
  11054. });
  11055. }
  11056. function openAddBridgePortModal() {
  11057. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11058. document.getElementById('bridge-port-modal-id').value = '';
  11059. populateBridgeSelect('bridge-port-modal-bridge');
  11060. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11061. document.getElementById('bridge-port-modal-pvid').value = '1';
  11062. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11063. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11064. document.getElementById('bridge-port-modal-horizon').value = '0';
  11065. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11066. document.getElementById('bridge-port-modal-priority').value = '128';
  11067. document.getElementById('bridge-port-modal-learn').checked = true;
  11068. document.getElementById('bridge-port-modal-comment').value = '';
  11069. document.getElementById('bridge-port-modal-disabled').checked = false;
  11070. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11071. }
  11072. function openEditBridgePortModal(id) {
  11073. const p = (state.bridgePorts || []).find(x => x.id === id);
  11074. if (!p) return;
  11075. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11076. document.getElementById('bridge-port-modal-id').value = p.id;
  11077. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11078. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11079. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11080. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11081. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11082. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11083. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11084. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11085. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11086. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11087. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11088. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11089. }
  11090. function closeBridgePortModal() {
  11091. document.getElementById('bridge-port-modal').classList.add('hidden');
  11092. }
  11093. async function submitSaveBridgePort(e) {
  11094. e.preventDefault();
  11095. const id = document.getElementById('bridge-port-modal-id').value;
  11096. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11097. const iface = document.getElementById('bridge-port-modal-interface').value;
  11098. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11099. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11100. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11101. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11102. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11103. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11104. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11105. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11106. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11107. try {
  11108. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11109. method: 'POST',
  11110. headers: { 'Content-Type': 'application/json' },
  11111. body: JSON.stringify({
  11112. id,
  11113. bridge,
  11114. interface: iface,
  11115. pvid,
  11116. frame_types: frameTypes,
  11117. ingress_filtering: ingressFiltering,
  11118. horizon,
  11119. path_cost: pathCost,
  11120. priority,
  11121. learn,
  11122. comment,
  11123. disabled
  11124. })
  11125. });
  11126. if (res.ok) {
  11127. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11128. closeBridgePortModal();
  11129. loadBridge();
  11130. fetchData(false);
  11131. } else {
  11132. const err = await res.json();
  11133. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11134. }
  11135. } catch (err) {
  11136. showToast('Error', err.message, 'error');
  11137. }
  11138. }
  11139. async function toggleBridgePortState(id, disabled) {
  11140. try {
  11141. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11142. method: 'POST',
  11143. headers: { 'Content-Type': 'application/json' },
  11144. body: JSON.stringify({ disabled })
  11145. });
  11146. if (res.ok) {
  11147. loadBridge();
  11148. fetchData(false);
  11149. }
  11150. } catch (err) {
  11151. showToast('Error', err.message, 'error');
  11152. }
  11153. }
  11154. async function deleteBridgePort(id) {
  11155. const p = (state.bridgePorts || []).find(x => x.id === id);
  11156. const iface = p ? p.interface : id;
  11157. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11158. try {
  11159. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11160. if (res.ok) {
  11161. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11162. loadBridge();
  11163. fetchData(false);
  11164. }
  11165. } catch (err) {
  11166. showToast('Error', err.message, 'error');
  11167. }
  11168. }
  11169. // ----------------- Bridge VLANs -----------------
  11170. function renderBridgeVLANs() {
  11171. const tbody = document.getElementById('bridge-vlans-table-body');
  11172. const empty = document.getElementById('bridge-empty-vlans');
  11173. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11174. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11175. if (!tbody) return;
  11176. tbody.innerHTML = '';
  11177. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11178. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11179. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11180. if (vlans.length === 0) {
  11181. empty?.classList.remove('hidden');
  11182. return;
  11183. }
  11184. empty?.classList.add('hidden');
  11185. vlans.forEach((v, idx) => {
  11186. const tr = document.createElement('tr');
  11187. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11188. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11189. ? 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(' ')
  11190. : '<span class="text-slate-600">none</span>';
  11191. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11192. ? 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(' ')
  11193. : '<span class="text-slate-600">none</span>';
  11194. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11195. tr.innerHTML = `
  11196. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11197. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11198. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11199. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11200. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11201. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11202. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11203. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11204. <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>
  11205. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11206. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11207. </td>
  11208. `;
  11209. tbody.appendChild(tr);
  11210. });
  11211. }
  11212. function openAddBridgeVLANModal() {
  11213. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11214. document.getElementById('bridge-vlan-modal-id').value = '';
  11215. populateBridgeSelect('bridge-vlan-modal-bridge');
  11216. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11217. document.getElementById('bridge-vlan-modal-comment').value = '';
  11218. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11219. updateBridgeVlanPortCheckboxes();
  11220. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11221. }
  11222. function openEditBridgeVLANModal(id) {
  11223. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11224. if (!v) return;
  11225. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11226. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11227. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11228. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11229. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11230. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11231. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11232. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11233. }
  11234. function closeBridgeVlanModal() {
  11235. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11236. }
  11237. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11238. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11239. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11240. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11241. if (!taggedBox || !untaggedBox) return;
  11242. // Ports belonging to the selected bridge
  11243. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11244. if (memberPorts.length === 0) {
  11245. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11246. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11247. return;
  11248. }
  11249. taggedBox.innerHTML = memberPorts.map(p => `
  11250. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11251. <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">
  11252. <span>${p.interface}</span>
  11253. </label>
  11254. `).join('');
  11255. untaggedBox.innerHTML = memberPorts.map(p => `
  11256. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11257. <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">
  11258. <span>${p.interface}</span>
  11259. </label>
  11260. `).join('');
  11261. }
  11262. async function submitSaveBridgeVLAN(e) {
  11263. e.preventDefault();
  11264. const id = document.getElementById('bridge-vlan-modal-id').value;
  11265. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11266. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11267. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11268. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11269. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11270. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11271. try {
  11272. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11273. method: 'POST',
  11274. headers: { 'Content-Type': 'application/json' },
  11275. body: JSON.stringify({
  11276. id,
  11277. bridge,
  11278. vlan_ids: vlanIDs,
  11279. tagged,
  11280. untagged,
  11281. comment,
  11282. disabled
  11283. })
  11284. });
  11285. if (res.ok) {
  11286. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11287. closeBridgeVlanModal();
  11288. loadBridge();
  11289. } else {
  11290. const err = await res.json();
  11291. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11292. }
  11293. } catch (err) {
  11294. showToast('Error', err.message, 'error');
  11295. }
  11296. }
  11297. async function toggleBridgeVLANState(id, disabled) {
  11298. try {
  11299. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11300. method: 'POST',
  11301. headers: { 'Content-Type': 'application/json' },
  11302. body: JSON.stringify({ disabled })
  11303. });
  11304. if (res.ok) loadBridge();
  11305. } catch (err) {
  11306. showToast('Error', err.message, 'error');
  11307. }
  11308. }
  11309. async function deleteBridgeVLAN(id) {
  11310. if (!confirm('Delete this bridge VLAN entry?')) return;
  11311. try {
  11312. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11313. if (res.ok) {
  11314. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11315. loadBridge();
  11316. }
  11317. } catch (err) {
  11318. showToast('Error', err.message, 'error');
  11319. }
  11320. }
  11321. // ----------------- Hosts / MAC Table -----------------
  11322. async function loadBridgeHosts() {
  11323. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11324. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11325. try {
  11326. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11327. const res = await fetch(url);
  11328. if (res.ok) {
  11329. state.bridgeHosts = await res.json();
  11330. renderBridgeHosts();
  11331. }
  11332. } catch (err) {
  11333. console.error('Failed to load bridge hosts:', err);
  11334. }
  11335. }
  11336. function renderBridgeHosts() {
  11337. const tbody = document.getElementById('bridge-hosts-table-body');
  11338. const empty = document.getElementById('bridge-empty-hosts');
  11339. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11340. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11341. if (!tbody) return;
  11342. tbody.innerHTML = '';
  11343. const hosts = (state.bridgeHosts || []).filter(h => {
  11344. if (!search) return true;
  11345. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11346. });
  11347. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11348. if (hosts.length === 0) {
  11349. empty?.classList.remove('hidden');
  11350. return;
  11351. }
  11352. empty?.classList.add('hidden');
  11353. hosts.forEach(h => {
  11354. const tr = document.createElement('tr');
  11355. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11356. let flagBadges = '';
  11357. 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>';
  11358. 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>';
  11359. 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>';
  11360. tr.innerHTML = `
  11361. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11362. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11363. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11364. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11365. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11366. <td class="py-2.5 px-3">${flagBadges}</td>
  11367. `;
  11368. tbody.appendChild(tr);
  11369. });
  11370. }
  11371. async function flushBridgeHosts() {
  11372. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11373. if (!selBridge) {
  11374. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11375. return;
  11376. }
  11377. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11378. try {
  11379. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11380. method: 'POST',
  11381. headers: { 'Content-Type': 'application/json' },
  11382. body: JSON.stringify({ bridge: selBridge })
  11383. });
  11384. if (res.ok) {
  11385. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11386. loadBridgeHosts();
  11387. }
  11388. } catch (err) {
  11389. showToast('Error', err.message, 'error');
  11390. }
  11391. }
  11392. // ----------------- Helpers -----------------
  11393. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11394. const sel = document.getElementById(selectId);
  11395. if (!sel) return;
  11396. const prevVal = currentVal || sel.value;
  11397. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11398. (state.bridges || []).forEach(b => {
  11399. const opt = document.createElement('option');
  11400. opt.value = b.name;
  11401. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11402. if (b.name === prevVal) opt.selected = true;
  11403. sel.appendChild(opt);
  11404. });
  11405. }
  11406. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11407. const sel = document.getElementById(selectId);
  11408. if (!sel) return;
  11409. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11410. // 1. Physical Interfaces
  11411. const grpPhys = document.createElement('optgroup');
  11412. grpPhys.label = 'Physical Interfaces';
  11413. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11414. const opt = document.createElement('option');
  11415. opt.value = i.name;
  11416. opt.innerText = `${i.name} (${i.role || i.type})`;
  11417. if (i.name === currentVal) opt.selected = true;
  11418. grpPhys.appendChild(opt);
  11419. });
  11420. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11421. // 2. VLAN Sub-interfaces
  11422. const grpVlans = document.createElement('optgroup');
  11423. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11424. (state.vlans || []).forEach(v => {
  11425. const opt = document.createElement('option');
  11426. opt.value = v.name;
  11427. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11428. if (v.name === currentVal) opt.selected = true;
  11429. grpVlans.appendChild(opt);
  11430. });
  11431. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11432. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11433. const grpEoip = document.createElement('optgroup');
  11434. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11435. (state.eoipTunnels || []).forEach(t => {
  11436. const opt = document.createElement('option');
  11437. opt.value = t.name;
  11438. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11439. if (t.name === currentVal) opt.selected = true;
  11440. grpEoip.appendChild(opt);
  11441. });
  11442. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11443. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11444. const grpVxlan = document.createElement('optgroup');
  11445. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11446. (state.vxlanTunnels || []).forEach(t => {
  11447. const opt = document.createElement('option');
  11448. opt.value = t.name;
  11449. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11450. if (t.name === currentVal) opt.selected = true;
  11451. grpVxlan.appendChild(opt);
  11452. });
  11453. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11454. }
  11455. // -------------------------------------------------------------
  11456. // DebTik Routing Filters Management (/routing filter)
  11457. // -------------------------------------------------------------
  11458. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11459. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11460. if (!state.rfSort) state.rfSort = {};
  11461. function switchRoutingFilterTab(tab) {
  11462. state.activeRoutingFilterTab = tab;
  11463. const tabs = ['rules', 'community-lists', 'as-lists'];
  11464. tabs.forEach(t => {
  11465. const btn = document.getElementById(`tab-rf-${t}`);
  11466. const content = document.getElementById(`tab-content-rf-${t}`);
  11467. if (btn) {
  11468. if (t === tab) {
  11469. 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';
  11470. } else {
  11471. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11472. }
  11473. }
  11474. if (content) {
  11475. if (t === tab) content.classList.remove('hidden');
  11476. else content.classList.add('hidden');
  11477. }
  11478. });
  11479. const chainContainer = document.getElementById('rf-chain-filter-container');
  11480. if (chainContainer) {
  11481. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11482. else chainContainer.classList.add('hidden');
  11483. }
  11484. renderRoutingFilters();
  11485. }
  11486. function selectFilterRow(tab, id) {
  11487. if (state.selectedFilterRow[tab] === id) {
  11488. delete state.selectedFilterRow[tab];
  11489. } else {
  11490. state.selectedFilterRow[tab] = id;
  11491. }
  11492. if (tab === 'rules') renderRoutingFilterRules();
  11493. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11494. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11495. }
  11496. function openRoutingFilterNewModal() {
  11497. const tab = state.activeRoutingFilterTab || 'rules';
  11498. if (tab === 'rules') openAddRoutingFilterModal();
  11499. else if (tab === 'community-lists') openAddCommunityListModal();
  11500. else if (tab === 'as-lists') openAddASListModal();
  11501. }
  11502. function toggleSelectedRoutingFilter(disabled) {
  11503. const tab = state.activeRoutingFilterTab || 'rules';
  11504. const id = state.selectedFilterRow[tab];
  11505. if (!id) {
  11506. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11507. return;
  11508. }
  11509. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11510. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11511. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11512. }
  11513. function removeSelectedRoutingFilter() {
  11514. const tab = state.activeRoutingFilterTab || 'rules';
  11515. const id = state.selectedFilterRow[tab];
  11516. if (!id) {
  11517. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11518. return;
  11519. }
  11520. if (tab === 'rules') deleteRoutingFilter(id);
  11521. else if (tab === 'community-lists') deleteCommunityList(id);
  11522. else if (tab === 'as-lists') deleteASList(id);
  11523. }
  11524. function searchRoutingFilters(q) {
  11525. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11526. renderRoutingFilters();
  11527. }
  11528. function sortFilterTable(tab, col) {
  11529. if (!state.rfSort) state.rfSort = {};
  11530. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11531. if (state.rfSort[tab].col === col) {
  11532. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11533. } else {
  11534. state.rfSort[tab].col = col;
  11535. state.rfSort[tab].asc = true;
  11536. }
  11537. const asc = state.rfSort[tab].asc;
  11538. let list = [];
  11539. if (tab === 'rules') list = state.routingFilters || [];
  11540. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11541. else if (tab === 'as-lists') list = state.routingASLists || [];
  11542. list.sort((a, b) => {
  11543. let valA = a[col] ?? '';
  11544. let valB = b[col] ?? '';
  11545. if (col === 'flags') {
  11546. valA = a.disabled ? 'X' : 'A';
  11547. valB = b.disabled ? 'X' : 'A';
  11548. }
  11549. if (typeof valA === 'number' && typeof valB === 'number') {
  11550. return asc ? valA - valB : valB - valA;
  11551. }
  11552. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11553. });
  11554. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11555. allCols.forEach(c => {
  11556. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11557. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11558. });
  11559. if (tab === 'rules') renderRoutingFilterRules();
  11560. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11561. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11562. }
  11563. function renderRoutingFilters() {
  11564. const navBadge = document.getElementById('badge-filters-count');
  11565. const allRules = state.routingFilters || [];
  11566. if (navBadge) navBadge.innerText = allRules.length;
  11567. // Populate chain filter select options and datalist
  11568. const chainSelect = document.getElementById('routing-filter-chain-select');
  11569. const chainDatalist = document.getElementById('dl-routing-chains');
  11570. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11571. if (chainSelect) {
  11572. const currentVal = state.filterChainSelected || 'all';
  11573. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11574. uniqueChains.map(ch => {
  11575. const count = allRules.filter(r => r.chain === ch).length;
  11576. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11577. }).join('');
  11578. chainSelect.value = currentVal;
  11579. }
  11580. if (chainDatalist) {
  11581. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11582. }
  11583. renderRoutingFilterRules();
  11584. renderRoutingFilterCommunityLists();
  11585. renderRoutingFilterASLists();
  11586. }
  11587. function filterRoutingFiltersByChain(chain) {
  11588. state.filterChainSelected = chain;
  11589. renderRoutingFilters();
  11590. }
  11591. // -------------------------------------------------------------
  11592. // TAB 1: RULES (/routing filter rule)
  11593. // -------------------------------------------------------------
  11594. function renderRoutingFilterRules() {
  11595. const tbody = document.getElementById('routing-filter-rules-tbody');
  11596. if (!tbody) return;
  11597. const empty = document.getElementById('rf-rules-empty');
  11598. const statusCount = document.getElementById('rf-status-count');
  11599. let list = (state.routingFilters || []).slice();
  11600. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11601. list = list.filter(r => r.chain === state.filterChainSelected);
  11602. }
  11603. const q = state.rfSearchQuery;
  11604. if (q) {
  11605. list = list.filter(r =>
  11606. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11607. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11608. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11609. (r.comment && r.comment.toLowerCase().includes(q))
  11610. );
  11611. }
  11612. if (!state.rfSort?.['rules']) {
  11613. list.sort((a, b) => {
  11614. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11615. return (a.rule_order || 0) - (b.rule_order || 0);
  11616. });
  11617. }
  11618. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11619. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11620. }
  11621. if (list.length === 0) {
  11622. tbody.innerHTML = '';
  11623. if (empty) empty.classList.remove('hidden');
  11624. return;
  11625. }
  11626. if (empty) empty.classList.add('hidden');
  11627. tbody.innerHTML = list.map(r => {
  11628. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11629. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11630. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11631. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11632. let ruleDisplay = '';
  11633. if (r.rule && r.rule.trim() !== '') {
  11634. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11635. } else {
  11636. let conds = [];
  11637. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11638. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11639. let act = r.action || 'accept';
  11640. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11641. }
  11642. return `
  11643. <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'}">
  11644. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11645. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11646. <td class="py-2 px-3">
  11647. <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>
  11648. </td>
  11649. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11650. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11651. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11652. <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>
  11653. <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>
  11654. <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'}">
  11655. ${r.disabled ? 'Enable' : 'Disable'}
  11656. </button>
  11657. <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">
  11658. Edit
  11659. </button>
  11660. <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">
  11661. ✕
  11662. </button>
  11663. </td>
  11664. </tr>
  11665. `;
  11666. }).join('');
  11667. }
  11668. // -------------------------------------------------------------
  11669. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11670. // -------------------------------------------------------------
  11671. function renderRoutingFilterCommunityLists() {
  11672. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11673. if (!tbody) return;
  11674. const empty = document.getElementById('rf-comm-lists-empty');
  11675. const statusCount = document.getElementById('rf-status-count');
  11676. let list = (state.routingCommunityLists || []).slice();
  11677. const q = state.rfSearchQuery;
  11678. if (q) {
  11679. list = list.filter(cl =>
  11680. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11681. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11682. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11683. );
  11684. }
  11685. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11686. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11687. }
  11688. if (list.length === 0) {
  11689. tbody.innerHTML = '';
  11690. if (empty) empty.classList.remove('hidden');
  11691. return;
  11692. }
  11693. if (empty) empty.classList.add('hidden');
  11694. tbody.innerHTML = list.map(cl => {
  11695. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11696. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11697. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11698. const commBadges = (cl.communities || []).map(c =>
  11699. `<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>`
  11700. ).join(' ');
  11701. return `
  11702. <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'}">
  11703. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11704. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11705. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11706. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11707. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11708. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11709. <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'}">
  11710. ${cl.disabled ? 'Enable' : 'Disable'}
  11711. </button>
  11712. <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">
  11713. Edit
  11714. </button>
  11715. <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">
  11716. ✕
  11717. </button>
  11718. </td>
  11719. </tr>
  11720. `;
  11721. }).join('');
  11722. }
  11723. // -------------------------------------------------------------
  11724. // TAB 4: AS LISTS (/routing filter num-list)
  11725. // -------------------------------------------------------------
  11726. function renderRoutingFilterASLists() {
  11727. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11728. if (!tbody) return;
  11729. const empty = document.getElementById('rf-as-lists-empty');
  11730. const statusCount = document.getElementById('rf-status-count');
  11731. let list = (state.routingASLists || []).slice();
  11732. const q = state.rfSearchQuery;
  11733. if (q) {
  11734. list = list.filter(al =>
  11735. (al.name && al.name.toLowerCase().includes(q)) ||
  11736. (al.range && al.range.toLowerCase().includes(q)) ||
  11737. (al.comment && al.comment.toLowerCase().includes(q))
  11738. );
  11739. }
  11740. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11741. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11742. }
  11743. if (list.length === 0) {
  11744. tbody.innerHTML = '';
  11745. if (empty) empty.classList.remove('hidden');
  11746. return;
  11747. }
  11748. if (empty) empty.classList.add('hidden');
  11749. tbody.innerHTML = list.map(al => {
  11750. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11751. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11752. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11753. return `
  11754. <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'}">
  11755. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11756. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11757. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11758. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11759. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11760. <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'}">
  11761. ${al.disabled ? 'Enable' : 'Disable'}
  11762. </button>
  11763. <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">
  11764. Edit
  11765. </button>
  11766. <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">
  11767. ✕
  11768. </button>
  11769. </td>
  11770. </tr>
  11771. `;
  11772. }).join('');
  11773. }
  11774. // -------------------------------------------------------------
  11775. // SNIPPETS & WIZARD HELPERS
  11776. // -------------------------------------------------------------
  11777. function insertRuleSnippet(type) {
  11778. const textarea = document.getElementById('modal-rf-rule');
  11779. if (!textarea) return;
  11780. let snippet = '';
  11781. switch (type) {
  11782. case 'accept-default':
  11783. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11784. break;
  11785. case 'drop-rfc1918':
  11786. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11787. break;
  11788. case 'len-24':
  11789. snippet = 'if (dst-len > 24) { reject; }';
  11790. break;
  11791. case 'local-pref-150':
  11792. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11793. break;
  11794. case 'as-prepend-2':
  11795. snippet = 'set bgp-path-prepend 2; accept;';
  11796. break;
  11797. case 'set-comm':
  11798. snippet = 'set bgp-communities.add 65000:100; accept;';
  11799. break;
  11800. case 'match-comm':
  11801. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11802. break;
  11803. case 'reject-all':
  11804. snippet = 'reject;';
  11805. break;
  11806. }
  11807. if (!snippet) return;
  11808. if (!textarea.value.trim()) {
  11809. textarea.value = snippet;
  11810. } else {
  11811. textarea.value = textarea.value.trim() + '\n' + snippet;
  11812. }
  11813. }
  11814. function generateScriptFromWizard() {
  11815. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11816. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11817. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11818. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11819. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11820. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11821. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11822. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11823. const conds = [];
  11824. if (pfx) {
  11825. if (pfxLen) {
  11826. if (pfxLen.includes('-')) {
  11827. const parts = pfxLen.split('-');
  11828. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11829. } else {
  11830. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11831. }
  11832. } else {
  11833. conds.push(`dst in ${pfx}`);
  11834. }
  11835. }
  11836. if (proto && proto !== 'any') {
  11837. conds.push(`protocol ${proto}`);
  11838. }
  11839. if (asp) {
  11840. conds.push(`bgp-as-path "${asp}"`);
  11841. }
  11842. if (comm) {
  11843. conds.push(`bgp-communities includes ${comm}`);
  11844. }
  11845. const actions = [];
  11846. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11847. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11848. if (act && act !== 'passthrough') {
  11849. actions.push(`${act};`);
  11850. }
  11851. let code = '';
  11852. if (conds.length > 0) {
  11853. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11854. } else {
  11855. code = actions.join(' ');
  11856. }
  11857. const textarea = document.getElementById('modal-rf-rule');
  11858. if (textarea) textarea.value = code;
  11859. }
  11860. // -------------------------------------------------------------
  11861. // MODAL CRUD: RULES (/routing filter rule)
  11862. // -------------------------------------------------------------
  11863. function openAddRoutingFilterModal(defaultChain = '') {
  11864. const form = document.getElementById('routing-filter-form');
  11865. if (form) form.reset();
  11866. const idEl = document.getElementById('modal-rf-id');
  11867. if (idEl) idEl.value = '';
  11868. const titleEl = document.getElementById('modal-rf-title');
  11869. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11870. const chainEl = document.getElementById('modal-rf-chain');
  11871. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11872. const orderEl = document.getElementById('modal-rf-order');
  11873. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11874. const ruleEl = document.getElementById('modal-rf-rule');
  11875. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11876. const disEl = document.getElementById('modal-rf-disabled');
  11877. if (disEl) disEl.checked = false;
  11878. const modal = document.getElementById('modal-routing-filter');
  11879. if (modal) modal.classList.remove('hidden');
  11880. }
  11881. function openEditRoutingFilterModal(id) {
  11882. const r = (state.routingFilters || []).find(item => item.id === id);
  11883. if (!r) return;
  11884. const idEl = document.getElementById('modal-rf-id');
  11885. if (idEl) idEl.value = r.id;
  11886. const titleEl = document.getElementById('modal-rf-title');
  11887. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11888. const chainEl = document.getElementById('modal-rf-chain');
  11889. if (chainEl) chainEl.value = r.chain || '';
  11890. const orderEl = document.getElementById('modal-rf-order');
  11891. if (orderEl) orderEl.value = r.rule_order || 10;
  11892. const ruleEl = document.getElementById('modal-rf-rule');
  11893. if (ruleEl) {
  11894. if (r.rule) {
  11895. ruleEl.value = r.rule;
  11896. } else {
  11897. let conds = [];
  11898. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11899. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11900. let act = r.action || 'accept';
  11901. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11902. }
  11903. }
  11904. const comEl = document.getElementById('modal-rf-comment');
  11905. if (comEl) comEl.value = r.comment || '';
  11906. const disEl = document.getElementById('modal-rf-disabled');
  11907. if (disEl) disEl.checked = !!r.disabled;
  11908. const modal = document.getElementById('modal-routing-filter');
  11909. if (modal) modal.classList.remove('hidden');
  11910. }
  11911. function closeRoutingFilterModal() {
  11912. const modal = document.getElementById('modal-routing-filter');
  11913. if (modal) modal.classList.add('hidden');
  11914. }
  11915. async function submitRoutingFilter(e) {
  11916. if (e) e.preventDefault();
  11917. const payload = {
  11918. id: document.getElementById('modal-rf-id').value,
  11919. chain: document.getElementById('modal-rf-chain').value.trim(),
  11920. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11921. rule: document.getElementById('modal-rf-rule').value.trim(),
  11922. comment: document.getElementById('modal-rf-comment').value.trim(),
  11923. disabled: document.getElementById('modal-rf-disabled').checked
  11924. };
  11925. try {
  11926. const res = await fetch(`${API_BASE}/routing/filters`, {
  11927. method: 'POST',
  11928. headers: { 'Content-Type': 'application/json' },
  11929. body: JSON.stringify(payload)
  11930. });
  11931. if (res.ok) {
  11932. closeRoutingFilterModal();
  11933. showToast('Success', 'Routing filter rule saved', 'success');
  11934. loadDynamicRouting();
  11935. } else {
  11936. const err = await res.json();
  11937. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11938. }
  11939. } catch (err) {
  11940. showToast('Error', err.message, 'error');
  11941. }
  11942. }
  11943. async function applyRoutingFilterForm() {
  11944. const payload = {
  11945. id: document.getElementById('modal-rf-id').value,
  11946. chain: document.getElementById('modal-rf-chain').value.trim(),
  11947. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11948. rule: document.getElementById('modal-rf-rule').value.trim(),
  11949. comment: document.getElementById('modal-rf-comment').value.trim(),
  11950. disabled: document.getElementById('modal-rf-disabled').checked
  11951. };
  11952. try {
  11953. const res = await fetch(`${API_BASE}/routing/filters`, {
  11954. method: 'POST',
  11955. headers: { 'Content-Type': 'application/json' },
  11956. body: JSON.stringify(payload)
  11957. });
  11958. if (res.ok) {
  11959. const data = await res.json();
  11960. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11961. showToast('Applied', 'Routing filter configuration applied', 'success');
  11962. loadDynamicRouting();
  11963. } else {
  11964. const err = await res.json();
  11965. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11966. }
  11967. } catch (err) {
  11968. showToast('Error', err.message, 'error');
  11969. }
  11970. }
  11971. async function moveRoutingFilterOrder(id, delta) {
  11972. const list = state.routingFilters || [];
  11973. const idx = list.findIndex(r => r.id === id);
  11974. if (idx < 0) return;
  11975. const targetIdx = idx + delta;
  11976. if (targetIdx < 0 || targetIdx >= list.length) return;
  11977. const currentOrder = list[idx].rule_order || 10;
  11978. const targetOrder = list[targetIdx].rule_order || 20;
  11979. list[idx].rule_order = targetOrder;
  11980. list[targetIdx].rule_order = currentOrder;
  11981. try {
  11982. await fetch(`${API_BASE}/routing/filters`, {
  11983. method: 'POST',
  11984. headers: { 'Content-Type': 'application/json' },
  11985. body: JSON.stringify(list[idx])
  11986. });
  11987. await fetch(`${API_BASE}/routing/filters`, {
  11988. method: 'POST',
  11989. headers: { 'Content-Type': 'application/json' },
  11990. body: JSON.stringify(list[targetIdx])
  11991. });
  11992. loadDynamicRouting();
  11993. } catch (e) {
  11994. console.error('Reorder error:', e);
  11995. }
  11996. }
  11997. async function deleteRoutingFilter(id) {
  11998. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11999. try {
  12000. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12001. if (res.ok) {
  12002. showToast('Deleted', 'Routing filter rule removed', 'info');
  12003. loadDynamicRouting();
  12004. } else {
  12005. const err = await res.json();
  12006. showToast('Error', err.error || 'Failed to delete rule', 'error');
  12007. }
  12008. } catch (err) {
  12009. showToast('Error', err.message, 'error');
  12010. }
  12011. }
  12012. async function toggleRoutingFilterState(id, disabled) {
  12013. try {
  12014. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  12015. method: 'POST',
  12016. headers: { 'Content-Type': 'application/json' },
  12017. body: JSON.stringify({ disabled })
  12018. });
  12019. if (res.ok) {
  12020. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12021. loadDynamicRouting();
  12022. } else {
  12023. const err = await res.json();
  12024. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12025. }
  12026. } catch (err) {
  12027. showToast('Error', err.message, 'error');
  12028. }
  12029. }
  12030. // -------------------------------------------------------------
  12031. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12032. // -------------------------------------------------------------
  12033. function openAddCommunityListModal() {
  12034. document.getElementById('modal-rf-cl-id').value = '';
  12035. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12036. document.getElementById('modal-rf-cl-name').value = '';
  12037. document.getElementById('modal-rf-cl-communities').value = '';
  12038. document.getElementById('modal-rf-cl-regexp').value = '';
  12039. document.getElementById('modal-rf-cl-comment').value = '';
  12040. document.getElementById('modal-rf-cl-disabled').checked = false;
  12041. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12042. }
  12043. function openEditCommunityListModal(id) {
  12044. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12045. if (!cl) return;
  12046. document.getElementById('modal-rf-cl-id').value = cl.id;
  12047. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12048. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12049. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12050. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12051. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12052. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12053. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12054. }
  12055. function closeCommunityListModal() {
  12056. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12057. }
  12058. async function submitCommunityList(e) {
  12059. e.preventDefault();
  12060. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12061. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12062. const payload = {
  12063. id: document.getElementById('modal-rf-cl-id').value,
  12064. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12065. communities: comms,
  12066. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12067. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12068. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12069. };
  12070. try {
  12071. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12072. method: 'POST',
  12073. headers: { 'Content-Type': 'application/json' },
  12074. body: JSON.stringify(payload)
  12075. });
  12076. if (res.ok) {
  12077. closeCommunityListModal();
  12078. showToast('Success', 'Community list saved', 'success');
  12079. loadDynamicRouting();
  12080. } else {
  12081. const err = await res.json();
  12082. showToast('Error', err.error || 'Failed to save community list', 'error');
  12083. }
  12084. } catch (err) {
  12085. showToast('Error', err.message, 'error');
  12086. }
  12087. }
  12088. async function deleteCommunityList(id) {
  12089. if (!confirm('Are you sure you want to delete this community list?')) return;
  12090. try {
  12091. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12092. if (res.ok) {
  12093. showToast('Deleted', 'Community list removed', 'info');
  12094. loadDynamicRouting();
  12095. } else {
  12096. const err = await res.json();
  12097. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12098. }
  12099. } catch (err) {
  12100. showToast('Error', err.message, 'error');
  12101. }
  12102. }
  12103. async function toggleCommunityListState(id, disabled) {
  12104. try {
  12105. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12106. method: 'POST',
  12107. headers: { 'Content-Type': 'application/json' },
  12108. body: JSON.stringify({ disabled })
  12109. });
  12110. if (res.ok) {
  12111. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12112. loadDynamicRouting();
  12113. } else {
  12114. const err = await res.json();
  12115. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12116. }
  12117. } catch (err) {
  12118. showToast('Error', err.message, 'error');
  12119. }
  12120. }
  12121. // -------------------------------------------------------------
  12122. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12123. // -------------------------------------------------------------
  12124. function openAddASListModal() {
  12125. document.getElementById('modal-rf-al-id').value = '';
  12126. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12127. document.getElementById('modal-rf-al-name').value = '';
  12128. document.getElementById('modal-rf-al-range').value = '';
  12129. document.getElementById('modal-rf-al-comment').value = '';
  12130. document.getElementById('modal-rf-al-disabled').checked = false;
  12131. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12132. }
  12133. function openEditASListModal(id) {
  12134. const al = (state.routingASLists || []).find(item => item.id === id);
  12135. if (!al) return;
  12136. document.getElementById('modal-rf-al-id').value = al.id;
  12137. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12138. document.getElementById('modal-rf-al-name').value = al.name || '';
  12139. document.getElementById('modal-rf-al-range').value = al.range || '';
  12140. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12141. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12142. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12143. }
  12144. function closeASListModal() {
  12145. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12146. }
  12147. async function submitASList(e) {
  12148. e.preventDefault();
  12149. const payload = {
  12150. id: document.getElementById('modal-rf-al-id').value,
  12151. name: document.getElementById('modal-rf-al-name').value.trim(),
  12152. range: document.getElementById('modal-rf-al-range').value.trim(),
  12153. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12154. disabled: document.getElementById('modal-rf-al-disabled').checked
  12155. };
  12156. try {
  12157. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12158. method: 'POST',
  12159. headers: { 'Content-Type': 'application/json' },
  12160. body: JSON.stringify(payload)
  12161. });
  12162. if (res.ok) {
  12163. closeASListModal();
  12164. showToast('Success', 'AS number list saved', 'success');
  12165. loadDynamicRouting();
  12166. } else {
  12167. const err = await res.json();
  12168. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12169. }
  12170. } catch (err) {
  12171. showToast('Error', err.message, 'error');
  12172. }
  12173. }
  12174. async function deleteASList(id) {
  12175. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12176. try {
  12177. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12178. if (res.ok) {
  12179. showToast('Deleted', 'AS list removed', 'info');
  12180. loadDynamicRouting();
  12181. } else {
  12182. const err = await res.json();
  12183. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12184. }
  12185. } catch (err) {
  12186. showToast('Error', err.message, 'error');
  12187. }
  12188. }
  12189. async function toggleASListState(id, disabled) {
  12190. try {
  12191. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12192. method: 'POST',
  12193. headers: { 'Content-Type': 'application/json' },
  12194. body: JSON.stringify({ disabled })
  12195. });
  12196. if (res.ok) {
  12197. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12198. loadDynamicRouting();
  12199. } else {
  12200. const err = await res.json();
  12201. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12202. }
  12203. } catch (err) {
  12204. showToast('Error', err.message, 'error');
  12205. }
  12206. }
  12207. // ==========================================
  12208. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12209. // ==========================================
  12210. function loadToolsView() {
  12211. populateToolsInterfaces();
  12212. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12213. }
  12214. function populateToolsInterfaces() {
  12215. const pingSel = document.getElementById('tools-ping-iface');
  12216. const traceSel = document.getElementById('tools-tr-iface');
  12217. let opts = '<option value="">Auto (Default Route)</option>';
  12218. if (Array.isArray(state.interfaces)) {
  12219. state.interfaces.forEach(iface => {
  12220. if (iface.name) {
  12221. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12222. }
  12223. });
  12224. }
  12225. if (pingSel) {
  12226. const cur = pingSel.value;
  12227. pingSel.innerHTML = opts;
  12228. if (cur) pingSel.value = cur;
  12229. }
  12230. if (traceSel) {
  12231. const cur = traceSel.value;
  12232. traceSel.innerHTML = opts;
  12233. if (cur) traceSel.value = cur;
  12234. }
  12235. }
  12236. function switchToolsSubTab(subTab) {
  12237. state.activeToolsSubTab = subTab;
  12238. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12239. tabs.forEach(t => {
  12240. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12241. const view = document.getElementById(`tools-view-${t}`);
  12242. if (btn) {
  12243. if (t === subTab) {
  12244. 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';
  12245. } else {
  12246. 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';
  12247. }
  12248. }
  12249. if (view) {
  12250. if (t === subTab) {
  12251. view.classList.remove('hidden');
  12252. } else {
  12253. view.classList.add('hidden');
  12254. }
  12255. }
  12256. });
  12257. }
  12258. function setPortPreset(port) {
  12259. const input = document.getElementById('tools-port-num');
  12260. if (input) input.value = port;
  12261. }
  12262. let pingAbortController = null;
  12263. let tracerouteAbortController = null;
  12264. function clearPingTable() {
  12265. const tbody = document.getElementById('tools-ping-tbody');
  12266. if (tbody) tbody.innerHTML = '';
  12267. const rawEl = document.getElementById('tools-ping-raw');
  12268. if (rawEl) rawEl.innerText = '';
  12269. const sentEl = document.getElementById('tools-ping-stat-sent');
  12270. if (sentEl) sentEl.innerText = '0';
  12271. const recvEl = document.getElementById('tools-ping-stat-recv');
  12272. if (recvEl) recvEl.innerText = '0';
  12273. const lossEl = document.getElementById('tools-ping-stat-loss');
  12274. if (lossEl) lossEl.innerText = '0%';
  12275. const avgEl = document.getElementById('tools-ping-stat-avg');
  12276. if (avgEl) avgEl.innerText = '0 ms';
  12277. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12278. if (minMaxEl) minMaxEl.innerText = '-';
  12279. const badge = document.getElementById('tools-ping-status-badge');
  12280. if (badge) {
  12281. badge.className = '';
  12282. badge.innerText = '';
  12283. }
  12284. }
  12285. function clearTracerouteTable() {
  12286. const tbody = document.getElementById('tools-tr-tbody');
  12287. if (tbody) tbody.innerHTML = '';
  12288. const rawEl = document.getElementById('tools-tr-raw');
  12289. if (rawEl) rawEl.innerText = '';
  12290. const statHops = document.getElementById('tools-tr-hops-count');
  12291. if (statHops) statHops.innerText = '0 Hops';
  12292. }
  12293. function resetPingButton() {
  12294. const btn = document.getElementById('tools-ping-btn');
  12295. const btnText = document.getElementById('tools-ping-btn-text');
  12296. const spinner = document.getElementById('tools-ping-spinner');
  12297. if (btn) {
  12298. btn.disabled = false;
  12299. 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';
  12300. }
  12301. if (btnText) btnText.innerText = 'Start Ping';
  12302. if (spinner) spinner.classList.add('hidden');
  12303. }
  12304. function setPingRunningButton() {
  12305. const btn = document.getElementById('tools-ping-btn');
  12306. const btnText = document.getElementById('tools-ping-btn-text');
  12307. const spinner = document.getElementById('tools-ping-spinner');
  12308. if (btn) {
  12309. btn.disabled = false;
  12310. 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';
  12311. }
  12312. if (btnText) btnText.innerText = 'Stop Ping';
  12313. if (spinner) spinner.classList.remove('hidden');
  12314. }
  12315. function resetTracerouteButton() {
  12316. const btn = document.getElementById('tools-tr-btn');
  12317. const btnText = document.getElementById('tools-tr-btn-text');
  12318. const spinner = document.getElementById('tools-tr-spinner');
  12319. if (btn) {
  12320. btn.disabled = false;
  12321. 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';
  12322. }
  12323. if (btnText) btnText.innerText = 'Start Traceroute';
  12324. if (spinner) spinner.classList.add('hidden');
  12325. }
  12326. function setTracerouteRunningButton() {
  12327. const btn = document.getElementById('tools-tr-btn');
  12328. const btnText = document.getElementById('tools-tr-btn-text');
  12329. const spinner = document.getElementById('tools-tr-spinner');
  12330. if (btn) {
  12331. btn.disabled = false;
  12332. 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';
  12333. }
  12334. if (btnText) btnText.innerText = 'Stop Traceroute';
  12335. if (spinner) spinner.classList.remove('hidden');
  12336. }
  12337. async function executePing(e) {
  12338. if (e) e.preventDefault();
  12339. // If already running, clicking the button stops the stream!
  12340. if (pingAbortController) {
  12341. pingAbortController.abort();
  12342. pingAbortController = null;
  12343. resetPingButton();
  12344. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12345. return;
  12346. }
  12347. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12348. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12349. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12350. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12351. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12352. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12353. if (!target) {
  12354. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12355. return;
  12356. }
  12357. clearPingTable();
  12358. const resCard = document.getElementById('tools-ping-results');
  12359. if (resCard) resCard.classList.remove('hidden');
  12360. pingAbortController = new AbortController();
  12361. setPingRunningButton();
  12362. try {
  12363. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12364. method: 'POST',
  12365. headers: { 'Content-Type': 'application/json' },
  12366. body: JSON.stringify({
  12367. target,
  12368. count,
  12369. size,
  12370. timeout,
  12371. interface: iface,
  12372. dont_frag: dontFrag
  12373. }),
  12374. signal: pingAbortController.signal
  12375. });
  12376. if (!res.ok) {
  12377. const errText = await res.text();
  12378. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12379. resetPingButton();
  12380. pingAbortController = null;
  12381. return;
  12382. }
  12383. const reader = res.body.getReader();
  12384. const decoder = new TextDecoder('utf-8');
  12385. let buffer = '';
  12386. while (true) {
  12387. const { done, value } = await reader.read();
  12388. if (done) break;
  12389. buffer += decoder.decode(value, { stream: true });
  12390. const blocks = buffer.split('\n\n');
  12391. buffer = blocks.pop() || '';
  12392. for (const block of blocks) {
  12393. const trimmed = block.trim();
  12394. if (!trimmed) continue;
  12395. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12396. try {
  12397. const evt = JSON.parse(line);
  12398. handleLivePingEvent(evt);
  12399. } catch (parseErr) {
  12400. console.warn('Ping SSE parse error:', parseErr, line);
  12401. }
  12402. }
  12403. }
  12404. } catch (err) {
  12405. if (err.name === 'AbortError') {
  12406. // User aborted normally
  12407. } else {
  12408. showToast('Ping Error', err.message, 'error');
  12409. }
  12410. } finally {
  12411. pingAbortController = null;
  12412. resetPingButton();
  12413. }
  12414. }
  12415. function handleLivePingEvent(evt) {
  12416. const sentEl = document.getElementById('tools-ping-stat-sent');
  12417. const recvEl = document.getElementById('tools-ping-stat-recv');
  12418. const lossEl = document.getElementById('tools-ping-stat-loss');
  12419. const avgEl = document.getElementById('tools-ping-stat-avg');
  12420. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12421. const badge = document.getElementById('tools-ping-status-badge');
  12422. const tbody = document.getElementById('tools-ping-tbody');
  12423. const rawEl = document.getElementById('tools-ping-raw');
  12424. if (evt.raw && rawEl) {
  12425. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12426. rawEl.scrollTop = rawEl.scrollHeight;
  12427. }
  12428. if (evt.type === 'reply') {
  12429. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12430. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12431. if (lossEl && evt.packet_loss_pct !== undefined) {
  12432. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12433. lossEl.className = evt.packet_loss_pct === 0
  12434. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12435. : (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');
  12436. }
  12437. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12438. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12439. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12440. }
  12441. if (badge) {
  12442. if (evt.packet_loss_pct === 0) {
  12443. 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';
  12444. badge.innerText = '100% OK';
  12445. } else {
  12446. 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';
  12447. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12448. }
  12449. }
  12450. if (tbody) {
  12451. const tr = document.createElement('tr');
  12452. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12453. tr.innerHTML = `
  12454. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12455. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12456. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12457. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12458. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12459. <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>
  12460. `;
  12461. tbody.appendChild(tr);
  12462. }
  12463. } else if (evt.type === 'timeout') {
  12464. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12465. if (lossEl && evt.packet_loss_pct !== undefined) {
  12466. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12467. 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';
  12468. }
  12469. if (badge) {
  12470. 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';
  12471. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12472. }
  12473. if (tbody) {
  12474. const tr = document.createElement('tr');
  12475. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12476. tr.innerHTML = `
  12477. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12478. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12479. <td class="py-2 px-3 text-slate-600">--</td>
  12480. <td class="py-2 px-3 text-slate-600">--</td>
  12481. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12482. <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>
  12483. `;
  12484. tbody.appendChild(tr);
  12485. }
  12486. } else if (evt.type === 'unreach') {
  12487. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12488. if (lossEl && evt.packet_loss_pct !== undefined) {
  12489. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12490. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12491. }
  12492. if (badge) {
  12493. 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';
  12494. badge.innerText = 'UNREACHABLE';
  12495. }
  12496. if (tbody) {
  12497. const tr = document.createElement('tr');
  12498. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12499. tr.innerHTML = `
  12500. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12501. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12502. <td class="py-2 px-3 text-slate-600">--</td>
  12503. <td class="py-2 px-3 text-slate-600">--</td>
  12504. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12505. <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>
  12506. `;
  12507. tbody.appendChild(tr);
  12508. }
  12509. } else if (evt.type === 'stats') {
  12510. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12511. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12512. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12513. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12514. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12515. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12516. }
  12517. } else if (evt.type === 'done') {
  12518. 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');
  12519. }
  12520. }
  12521. async function executeTraceroute(e) {
  12522. if (e) e.preventDefault();
  12523. if (tracerouteAbortController) {
  12524. tracerouteAbortController.abort();
  12525. tracerouteAbortController = null;
  12526. resetTracerouteButton();
  12527. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12528. return;
  12529. }
  12530. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12531. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12532. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12533. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12534. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12535. if (!target) {
  12536. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12537. return;
  12538. }
  12539. clearTracerouteTable();
  12540. const resCard = document.getElementById('tools-tr-results');
  12541. if (resCard) resCard.classList.remove('hidden');
  12542. tracerouteAbortController = new AbortController();
  12543. setTracerouteRunningButton();
  12544. try {
  12545. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12546. method: 'POST',
  12547. headers: { 'Content-Type': 'application/json' },
  12548. body: JSON.stringify({
  12549. target,
  12550. max_hops: maxHops,
  12551. protocol,
  12552. interface: iface,
  12553. resolve
  12554. }),
  12555. signal: tracerouteAbortController.signal
  12556. });
  12557. if (!res.ok) {
  12558. const errText = await res.text();
  12559. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12560. resetTracerouteButton();
  12561. tracerouteAbortController = null;
  12562. return;
  12563. }
  12564. const reader = res.body.getReader();
  12565. const decoder = new TextDecoder('utf-8');
  12566. let buffer = '';
  12567. while (true) {
  12568. const { done, value } = await reader.read();
  12569. if (done) break;
  12570. buffer += decoder.decode(value, { stream: true });
  12571. const blocks = buffer.split('\n\n');
  12572. buffer = blocks.pop() || '';
  12573. for (const block of blocks) {
  12574. const trimmed = block.trim();
  12575. if (!trimmed) continue;
  12576. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12577. try {
  12578. const evt = JSON.parse(line);
  12579. handleLiveTracerouteEvent(evt);
  12580. } catch (parseErr) {
  12581. console.warn('Traceroute SSE parse error:', parseErr, line);
  12582. }
  12583. }
  12584. }
  12585. } catch (err) {
  12586. if (err.name === 'AbortError') {
  12587. // User aborted normally
  12588. } else {
  12589. showToast('Traceroute Error', err.message, 'error');
  12590. }
  12591. } finally {
  12592. tracerouteAbortController = null;
  12593. resetTracerouteButton();
  12594. }
  12595. }
  12596. function handleLiveTracerouteEvent(evt) {
  12597. const statHops = document.getElementById('tools-tr-hops-count');
  12598. const tbody = document.getElementById('tools-tr-tbody');
  12599. const rawEl = document.getElementById('tools-tr-raw');
  12600. if (evt.raw && rawEl) {
  12601. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12602. rawEl.scrollTop = rawEl.scrollHeight;
  12603. }
  12604. if (evt.hops_count !== undefined && statHops) {
  12605. statHops.innerText = `${evt.hops_count} Hops`;
  12606. }
  12607. if (evt.type === 'hop' && evt.hop && tbody) {
  12608. const h = evt.hop;
  12609. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12610. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12611. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12612. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12613. const tr = document.createElement('tr');
  12614. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12615. tr.innerHTML = `
  12616. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12617. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12618. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12619. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12620. <td class="py-2.5 px-3 text-right">
  12621. ${isTimeout
  12622. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12623. : '<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>'}
  12624. </td>
  12625. `;
  12626. tbody.appendChild(tr);
  12627. } else if (evt.type === 'done') {
  12628. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12629. }
  12630. }
  12631. async function executeMTR(e) {
  12632. if (e) e.preventDefault();
  12633. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12634. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12635. if (!target) {
  12636. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12637. return;
  12638. }
  12639. const btn = document.getElementById('tools-mtr-btn');
  12640. const spinner = document.getElementById('tools-mtr-spinner');
  12641. if (btn) btn.disabled = true;
  12642. if (spinner) spinner.classList.remove('hidden');
  12643. try {
  12644. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12645. method: 'POST',
  12646. headers: { 'Content-Type': 'application/json' },
  12647. body: JSON.stringify({ target, count: cycles })
  12648. });
  12649. const data = await res.json();
  12650. if (!res.ok) {
  12651. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12652. return;
  12653. }
  12654. const resCard = document.getElementById('tools-mtr-results');
  12655. if (resCard) resCard.classList.remove('hidden');
  12656. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12657. const statHops = document.getElementById('tools-mtr-hops-count');
  12658. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12659. const tbody = document.getElementById('tools-mtr-tbody');
  12660. if (tbody) {
  12661. if (hopsCount > 0) {
  12662. tbody.innerHTML = data.hops.map(h => {
  12663. 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');
  12664. return `
  12665. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12666. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12667. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12668. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12669. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12670. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12671. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12672. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12673. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12674. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12675. </tr>
  12676. `;
  12677. }).join('');
  12678. } else {
  12679. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12680. }
  12681. }
  12682. const rawEl = document.getElementById('tools-mtr-raw');
  12683. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12684. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12685. } catch (err) {
  12686. showToast('MTR Error', err.message, 'error');
  12687. } finally {
  12688. if (btn) btn.disabled = false;
  12689. if (spinner) spinner.classList.add('hidden');
  12690. }
  12691. }
  12692. async function executeDNS(e) {
  12693. if (e) e.preventDefault();
  12694. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12695. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12696. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12697. if (!domain) {
  12698. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12699. return;
  12700. }
  12701. const btn = document.getElementById('tools-dns-btn');
  12702. const spinner = document.getElementById('tools-dns-spinner');
  12703. if (btn) btn.disabled = true;
  12704. if (spinner) spinner.classList.remove('hidden');
  12705. try {
  12706. const res = await fetch(`${API_BASE}/tools/dns`, {
  12707. method: 'POST',
  12708. headers: { 'Content-Type': 'application/json' },
  12709. body: JSON.stringify({ domain, type, server })
  12710. });
  12711. const data = await res.json();
  12712. if (!res.ok) {
  12713. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12714. return;
  12715. }
  12716. const resCard = document.getElementById('tools-dns-results');
  12717. if (resCard) resCard.classList.remove('hidden');
  12718. const metaEl = document.getElementById('tools-dns-meta');
  12719. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12720. const tbody = document.getElementById('tools-dns-tbody');
  12721. if (tbody) {
  12722. if (Array.isArray(data.records) && data.records.length > 0) {
  12723. tbody.innerHTML = data.records.map(r => `
  12724. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12725. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12726. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12727. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12728. <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>
  12729. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12730. </tr>
  12731. `).join('');
  12732. } else {
  12733. 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>`;
  12734. }
  12735. }
  12736. const rawEl = document.getElementById('tools-dns-raw');
  12737. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12738. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12739. } catch (err) {
  12740. showToast('DNS Error', err.message, 'error');
  12741. } finally {
  12742. if (btn) btn.disabled = false;
  12743. if (spinner) spinner.classList.add('hidden');
  12744. }
  12745. }
  12746. async function executePortProbe(e) {
  12747. if (e) e.preventDefault();
  12748. const target = document.getElementById('tools-port-target')?.value?.trim();
  12749. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12750. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12751. if (!target || !port) {
  12752. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12753. return;
  12754. }
  12755. const btn = document.getElementById('tools-port-btn');
  12756. const spinner = document.getElementById('tools-port-spinner');
  12757. if (btn) btn.disabled = true;
  12758. if (spinner) spinner.classList.remove('hidden');
  12759. try {
  12760. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12761. method: 'POST',
  12762. headers: { 'Content-Type': 'application/json' },
  12763. body: JSON.stringify({ target, port, timeout })
  12764. });
  12765. const data = await res.json();
  12766. if (!res.ok) {
  12767. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12768. return;
  12769. }
  12770. const resCard = document.getElementById('tools-port-results');
  12771. if (resCard) resCard.classList.remove('hidden');
  12772. const banner = document.getElementById('tools-port-banner');
  12773. const icon = document.getElementById('tools-port-icon');
  12774. const title = document.getElementById('tools-port-title');
  12775. const sub = document.getElementById('tools-port-sub');
  12776. const latency = document.getElementById('tools-port-latency');
  12777. if (data.open) {
  12778. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12779. if (icon) {
  12780. 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';
  12781. icon.innerText = '✓';
  12782. }
  12783. if (title) {
  12784. title.className = 'text-sm font-bold text-emerald-300';
  12785. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12786. }
  12787. if (sub) {
  12788. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12789. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12790. }
  12791. if (latency) {
  12792. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12793. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12794. }
  12795. } else {
  12796. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12797. if (icon) {
  12798. 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';
  12799. icon.innerText = '✕';
  12800. }
  12801. if (title) {
  12802. title.className = 'text-sm font-bold text-rose-300';
  12803. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12804. }
  12805. if (sub) {
  12806. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12807. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12808. }
  12809. if (latency) {
  12810. latency.className = 'text-base font-bold font-mono text-slate-500';
  12811. latency.innerText = '--';
  12812. }
  12813. }
  12814. const rawEl = document.getElementById('tools-port-raw');
  12815. 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'}`);
  12816. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12817. } catch (err) {
  12818. showToast('Probe Error', err.message, 'error');
  12819. } finally {
  12820. if (btn) btn.disabled = false;
  12821. if (spinner) spinner.classList.add('hidden');
  12822. }
  12823. }
  12824. // ==========================================
  12825. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12826. // ==========================================
  12827. async function loadDHCPClients(showToastMsg = false) {
  12828. try {
  12829. const [clientsRes, sumRes] = await Promise.all([
  12830. fetch(`${API_BASE}/dhcp/clients`),
  12831. fetch(`${API_BASE}/dhcp/clients/summary`)
  12832. ]);
  12833. if (clientsRes.ok) {
  12834. state.dhcpClients = await clientsRes.json();
  12835. }
  12836. if (sumRes.ok) {
  12837. state.dhcpSummary = await sumRes.json();
  12838. }
  12839. renderDHCPClients();
  12840. updateDHCPSummaryCards();
  12841. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12842. if (bDhcp && state.dhcpSummary) {
  12843. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12844. }
  12845. if (showToastMsg) {
  12846. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12847. }
  12848. } catch (err) {
  12849. console.error('Failed to load DHCP clients:', err);
  12850. if (showToastMsg) {
  12851. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12852. }
  12853. }
  12854. }
  12855. function updateDHCPSummaryCards() {
  12856. const sum = state.dhcpSummary || {
  12857. total_clients: (state.dhcpClients || []).length,
  12858. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12859. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12860. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12861. };
  12862. const totalEl = document.getElementById('dhcp-stat-total');
  12863. const boundEl = document.getElementById('dhcp-stat-bound');
  12864. const searchEl = document.getElementById('dhcp-stat-searching');
  12865. const disEl = document.getElementById('dhcp-stat-disabled');
  12866. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12867. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12868. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12869. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12870. }
  12871. function renderDHCPClients() {
  12872. const tbody = document.getElementById('dhcp-clients-tbody');
  12873. const emptyState = document.getElementById('dhcp-clients-empty');
  12874. if (!tbody) return;
  12875. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12876. if (clients.length === 0) {
  12877. tbody.innerHTML = '';
  12878. if (emptyState) emptyState.classList.remove('hidden');
  12879. return;
  12880. }
  12881. if (emptyState) emptyState.classList.add('hidden');
  12882. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12883. if (tbody.dataset.sig === sig) return;
  12884. tbody.dataset.sig = sig;
  12885. tbody.innerHTML = clients.map(c => {
  12886. let statusBadge = '';
  12887. if (!c.enabled) {
  12888. 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>';
  12889. } else if (c.status === 'bound') {
  12890. 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>';
  12891. } else if (c.status === 'searching') {
  12892. 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>';
  12893. } else if (c.status === 'stopped') {
  12894. 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>';
  12895. } else {
  12896. 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>`;
  12897. }
  12898. 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>';
  12899. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12900. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12901. 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>';
  12902. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12903. // Option flags
  12904. const flags = [];
  12905. 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>');
  12906. 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>');
  12907. 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>');
  12908. 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>`);
  12909. return `
  12910. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12911. <td class="py-3 px-4">
  12912. <div class="flex items-center gap-2">
  12913. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12914. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12915. </div>
  12916. </td>
  12917. <td class="py-3 px-4">${statusBadge}</td>
  12918. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12919. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12920. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12921. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12922. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12923. <td class="py-3 px-4">
  12924. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12925. </td>
  12926. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12927. ${c.enabled ? `
  12928. <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>
  12929. <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>
  12930. <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>
  12931. ` : `
  12932. <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>
  12933. `}
  12934. <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>
  12935. <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>
  12936. </td>
  12937. </tr>
  12938. `;
  12939. }).join('');
  12940. }
  12941. function openDHCPClientModal(clientId = null) {
  12942. const modal = document.getElementById('modal-dhcp-client');
  12943. if (!modal) return;
  12944. const title = document.getElementById('modal-dhcp-title');
  12945. const idInput = document.getElementById('modal-dhcp-id');
  12946. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12947. const distInput = document.getElementById('modal-dhcp-distance');
  12948. const commentInput = document.getElementById('modal-dhcp-comment');
  12949. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12950. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12951. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12952. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12953. // Populate interfaces
  12954. if (ifaceSelect) {
  12955. let opts = '<option value="">Select interface...</option>';
  12956. const allIfaces = state.interfaces || [];
  12957. const allVlans = state.vlans || [];
  12958. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12959. // Group 1: Physical & Bridge Interfaces
  12960. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12961. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12962. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12963. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12964. });
  12965. opts += '</optgroup>';
  12966. // Group 2: VLAN Interfaces
  12967. if (allVlans.length > 0) {
  12968. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12969. allVlans.forEach(v => {
  12970. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12971. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12972. });
  12973. opts += '</optgroup>';
  12974. }
  12975. ifaceSelect.innerHTML = opts;
  12976. }
  12977. if (clientId) {
  12978. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12979. if (client) {
  12980. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12981. if (idInput) idInput.value = client.id;
  12982. if (ifaceSelect) {
  12983. ifaceSelect.value = client.interface;
  12984. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12985. }
  12986. if (distInput) distInput.value = client.default_route_distance || 1;
  12987. if (commentInput) commentInput.value = client.comment || '';
  12988. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12989. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12990. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12991. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12992. }
  12993. } else {
  12994. if (title) title.innerText = 'Add DHCP Client';
  12995. if (idInput) idInput.value = '';
  12996. if (ifaceSelect) {
  12997. ifaceSelect.value = '';
  12998. ifaceSelect.disabled = false;
  12999. }
  13000. if (distInput) distInput.value = 1;
  13001. if (commentInput) commentInput.value = '';
  13002. if (defRouteCheck) defRouteCheck.checked = true;
  13003. if (peerDnsCheck) peerDnsCheck.checked = true;
  13004. if (peerNtpCheck) peerNtpCheck.checked = true;
  13005. if (enabledCheck) enabledCheck.checked = true;
  13006. }
  13007. modal.classList.remove('hidden');
  13008. }
  13009. function openDHCPClientModalForIface(ifaceName) {
  13010. openDHCPClientModal();
  13011. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13012. if (ifaceSelect && ifaceName) {
  13013. ifaceSelect.value = ifaceName;
  13014. }
  13015. }
  13016. function closeDHCPClientModal() {
  13017. const modal = document.getElementById('modal-dhcp-client');
  13018. if (modal) modal.classList.add('hidden');
  13019. }
  13020. async function submitSaveDHCPClient(e) {
  13021. if (e) e.preventDefault();
  13022. const id = document.getElementById('modal-dhcp-id')?.value;
  13023. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13024. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13025. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13026. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13027. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13028. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13029. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13030. if (!id && !iface) {
  13031. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13032. return;
  13033. }
  13034. try {
  13035. let res;
  13036. if (id) {
  13037. // PUT update
  13038. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13039. method: 'PUT',
  13040. headers: { 'Content-Type': 'application/json' },
  13041. body: JSON.stringify({
  13042. enabled,
  13043. add_default_route: defRoute,
  13044. default_route_distance: distance,
  13045. use_peer_dns: peerDns,
  13046. use_peer_ntp: peerNtp,
  13047. comment
  13048. })
  13049. });
  13050. } else {
  13051. // POST create
  13052. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13053. method: 'POST',
  13054. headers: { 'Content-Type': 'application/json' },
  13055. body: JSON.stringify({
  13056. interface: iface,
  13057. enabled,
  13058. add_default_route: defRoute,
  13059. default_route_distance: distance,
  13060. use_peer_dns: peerDns,
  13061. use_peer_ntp: peerNtp,
  13062. comment
  13063. })
  13064. });
  13065. }
  13066. const data = await res.json();
  13067. if (!res.ok) {
  13068. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13069. return;
  13070. }
  13071. closeDHCPClientModal();
  13072. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13073. await loadDHCPClients();
  13074. fetchData(); // refresh interfaces list with new lease/status
  13075. } catch (err) {
  13076. showToast('Error', err.message, 'error');
  13077. }
  13078. }
  13079. async function toggleDHCPClientState(id, enabled) {
  13080. try {
  13081. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13082. method: 'POST',
  13083. headers: { 'Content-Type': 'application/json' },
  13084. body: JSON.stringify({ enabled })
  13085. });
  13086. const data = await res.json();
  13087. if (!res.ok) {
  13088. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13089. return;
  13090. }
  13091. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13092. await loadDHCPClients();
  13093. fetchData();
  13094. } catch (err) {
  13095. showToast('Error', err.message, 'error');
  13096. }
  13097. }
  13098. async function renewDHCPClient(id) {
  13099. try {
  13100. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13101. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13102. method: 'POST'
  13103. });
  13104. const data = await res.json();
  13105. if (!res.ok) {
  13106. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13107. return;
  13108. }
  13109. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13110. setTimeout(() => {
  13111. loadDHCPClients();
  13112. fetchData();
  13113. }, 1500);
  13114. } catch (err) {
  13115. showToast('Error', err.message, 'error');
  13116. }
  13117. }
  13118. async function releaseDHCPClient(id) {
  13119. try {
  13120. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13121. method: 'POST'
  13122. });
  13123. const data = await res.json();
  13124. if (!res.ok) {
  13125. showToast('Error', data.error || 'Failed to release lease', 'error');
  13126. return;
  13127. }
  13128. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13129. await loadDHCPClients();
  13130. fetchData();
  13131. } catch (err) {
  13132. showToast('Error', err.message, 'error');
  13133. }
  13134. }
  13135. async function deleteDHCPClient(id, ifaceName) {
  13136. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13137. return;
  13138. }
  13139. try {
  13140. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13141. method: 'DELETE'
  13142. });
  13143. const data = await res.json();
  13144. if (!res.ok) {
  13145. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13146. return;
  13147. }
  13148. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13149. await loadDHCPClients();
  13150. fetchData();
  13151. } catch (err) {
  13152. showToast('Error', err.message, 'error');
  13153. }
  13154. }
  13155. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13156. async function loadDHCPServer(populate = true) {
  13157. try {
  13158. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13159. fetch(`${API_BASE}/dhcp-server/summary`),
  13160. fetch(`${API_BASE}/dhcp-server/servers`),
  13161. fetch(`${API_BASE}/dhcp-server/networks`),
  13162. fetch(`${API_BASE}/dhcp-server/leases`),
  13163. fetch(`${API_BASE}/dhcp-server/options`)
  13164. ]);
  13165. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13166. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13167. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13168. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13169. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13170. const sum = state.dhcpServerSummary || {};
  13171. const srvs = state.dhcpServers || [];
  13172. const nets = state.dhcpNetworks || [];
  13173. const leases = state.dhcpLeases || [];
  13174. const opts = state.dhcpOptions || [];
  13175. // KPI Cards
  13176. const statActive = document.getElementById('dhcp-server-stat-active');
  13177. if (statActive) {
  13178. const activeCount = srvs.filter(s => s.running).length;
  13179. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13180. }
  13181. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13182. if (statLeases) {
  13183. statLeases.innerText = leases.length;
  13184. }
  13185. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13186. if (statLeasesSub) {
  13187. const dyn = leases.filter(l => l.dynamic).length;
  13188. const st = leases.filter(l => !l.dynamic).length;
  13189. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13190. }
  13191. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13192. if (statNetworks) {
  13193. statNetworks.innerText = nets.length;
  13194. }
  13195. // Subtab Badges
  13196. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13197. if (bSrv) bSrv.innerText = srvs.length;
  13198. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13199. if (bNet) bNet.innerText = nets.length;
  13200. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13201. if (bLease) bLease.innerText = leases.length;
  13202. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13203. if (bOpt) bOpt.innerText = opts.length;
  13204. // Sidebar Badge
  13205. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13206. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13207. renderCurrentDHCPServerTab();
  13208. } catch (err) {
  13209. console.error('Failed to load DHCP Server:', err);
  13210. }
  13211. }
  13212. function switchDHCPServerTab(tab) {
  13213. state.dhcpServerTab = tab;
  13214. const tabs = ['servers', 'networks', 'leases', 'options'];
  13215. tabs.forEach(t => {
  13216. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13217. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13218. if (panel) {
  13219. if (t === tab) panel.classList.remove('hidden');
  13220. else panel.classList.add('hidden');
  13221. }
  13222. if (btn) {
  13223. if (t === tab) {
  13224. 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';
  13225. } else {
  13226. 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';
  13227. }
  13228. }
  13229. });
  13230. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13231. if (addBtn) {
  13232. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13233. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13234. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13235. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13236. }
  13237. renderCurrentDHCPServerTab();
  13238. }
  13239. function handleDHCPServerPrimaryAdd() {
  13240. const tab = state.dhcpServerTab || 'servers';
  13241. if (tab === 'servers') openAddDHCPServerModal();
  13242. else if (tab === 'networks') openAddDHCPNetworkModal();
  13243. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13244. else if (tab === 'options') openAddDHCPOptionModal();
  13245. }
  13246. function renderCurrentDHCPServerTab() {
  13247. const tab = state.dhcpServerTab || 'servers';
  13248. if (tab === 'servers') renderDHCPServers();
  13249. else if (tab === 'networks') renderDHCPNetworks();
  13250. else if (tab === 'leases') renderDHCPLeases();
  13251. else if (tab === 'options') renderDHCPOptions();
  13252. }
  13253. function renderDHCPServers() {
  13254. const tbody = document.getElementById('dhcp-server-tbody');
  13255. const empty = document.getElementById('dhcp-server-empty');
  13256. if (!tbody) return;
  13257. const servers = state.dhcpServers || [];
  13258. if (servers.length === 0) {
  13259. tbody.innerHTML = '';
  13260. empty?.classList.remove('hidden');
  13261. return;
  13262. }
  13263. empty?.classList.add('hidden');
  13264. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13265. if (tbody.dataset.sig === sig) return;
  13266. tbody.dataset.sig = sig;
  13267. tbody.innerHTML = '';
  13268. servers.forEach(s => {
  13269. const tr = document.createElement('tr');
  13270. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13271. tr.innerHTML = `
  13272. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13273. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13274. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13275. <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>
  13276. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13277. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13278. <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>
  13279. <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>
  13280. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13281. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13282. <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>
  13283. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13284. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13285. </td>
  13286. `;
  13287. tbody.appendChild(tr);
  13288. });
  13289. }
  13290. function renderDHCPNetworks() {
  13291. const tbody = document.getElementById('dhcp-networks-tbody');
  13292. const empty = document.getElementById('dhcp-networks-empty');
  13293. if (!tbody) return;
  13294. tbody.innerHTML = '';
  13295. const networks = state.dhcpNetworks || [];
  13296. if (networks.length === 0) {
  13297. empty?.classList.remove('hidden');
  13298. return;
  13299. }
  13300. empty?.classList.add('hidden');
  13301. networks.forEach(n => {
  13302. const tr = document.createElement('tr');
  13303. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13304. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13305. const optionsChips = (n.dhcp_options || []).map(optId => {
  13306. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13307. if (!opt) return '';
  13308. 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>`;
  13309. }).filter(Boolean).join('');
  13310. tr.innerHTML = `
  13311. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13312. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13313. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13314. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13315. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13316. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13317. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13318. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13319. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13320. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13321. </td>
  13322. `;
  13323. tbody.appendChild(tr);
  13324. });
  13325. }
  13326. function renderDHCPLeases() {
  13327. const tbody = document.getElementById('dhcp-leases-tbody');
  13328. const empty = document.getElementById('dhcp-leases-empty');
  13329. if (!tbody) return;
  13330. tbody.innerHTML = '';
  13331. const leases = state.dhcpLeases || [];
  13332. if (leases.length === 0) {
  13333. empty?.classList.remove('hidden');
  13334. return;
  13335. }
  13336. empty?.classList.add('hidden');
  13337. leases.forEach(l => {
  13338. const tr = document.createElement('tr');
  13339. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13340. 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>';
  13341. const statusBadge = l.status === 'bound'
  13342. ? '<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>'
  13343. : l.status === 'static'
  13344. ? '<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>'
  13345. : '<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>';
  13346. const makeStaticBtn = l.dynamic
  13347. ? `<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>`
  13348. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13349. tr.innerHTML = `
  13350. <td class="py-2.5 px-3 text-center">${flag}</td>
  13351. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13352. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13353. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13354. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13355. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13356. <td class="py-2.5 px-3">${statusBadge}</td>
  13357. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13358. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13359. ${makeStaticBtn}
  13360. </td>
  13361. `;
  13362. tbody.appendChild(tr);
  13363. });
  13364. }
  13365. function renderDHCPOptions() {
  13366. const tbody = document.getElementById('dhcp-options-tbody');
  13367. const empty = document.getElementById('dhcp-options-empty');
  13368. if (!tbody) return;
  13369. tbody.innerHTML = '';
  13370. const options = state.dhcpOptions || [];
  13371. if (options.length === 0) {
  13372. empty?.classList.remove('hidden');
  13373. return;
  13374. }
  13375. empty?.classList.add('hidden');
  13376. options.forEach(o => {
  13377. const tr = document.createElement('tr');
  13378. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13379. tr.innerHTML = `
  13380. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13381. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13382. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13383. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13384. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13385. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13386. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13387. </td>
  13388. `;
  13389. tbody.appendChild(tr);
  13390. });
  13391. }
  13392. // ==================== MODALS & ACTIONS: SERVER ====================
  13393. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13394. const sel = document.getElementById(elemId);
  13395. if (!sel) return;
  13396. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13397. const networks = state.dhcpNetworks || [];
  13398. networks.forEach(n => {
  13399. const opt = document.createElement('option');
  13400. opt.value = n.address;
  13401. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13402. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13403. opt.selected = true;
  13404. }
  13405. sel.appendChild(opt);
  13406. });
  13407. }
  13408. function onDHCPServerNetworkChange() {
  13409. const netSel = document.getElementById('dhcp-server-modal-network');
  13410. if (!netSel) return;
  13411. const netVal = netSel.value;
  13412. if (!netVal) return;
  13413. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13414. if (!poolInput) return;
  13415. // Auto-calculate suggested address pool based on subnet CIDR
  13416. const parts = netVal.split('/');
  13417. const ip = parts[0];
  13418. const cidr = parseInt(parts[1] || '24', 10);
  13419. if (cidr === 24) {
  13420. const octets = ip.split('.');
  13421. if (octets.length === 4) {
  13422. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13423. poolInput.value = `${base}.10-${base}.254`;
  13424. }
  13425. }
  13426. }
  13427. function openAddDHCPServerModal() {
  13428. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13429. document.getElementById('dhcp-server-modal-id').value = '';
  13430. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13431. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13432. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13433. document.getElementById('dhcp-server-modal-comment').value = '';
  13434. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13435. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13436. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13437. const networks = state.dhcpNetworks || [];
  13438. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13439. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13440. if (defaultNet) {
  13441. onDHCPServerNetworkChange();
  13442. }
  13443. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13444. }
  13445. function openEditDHCPServerModal(id) {
  13446. const s = (state.dhcpServers || []).find(item => item.id === id);
  13447. if (!s) return;
  13448. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13449. document.getElementById('dhcp-server-modal-id').value = s.id;
  13450. document.getElementById('dhcp-server-modal-name').value = s.name;
  13451. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13452. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13453. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13454. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13455. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13456. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13457. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13458. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13459. }
  13460. function closeDHCPServerModal() {
  13461. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13462. }
  13463. async function submitSaveDHCPServer(e) {
  13464. e.preventDefault();
  13465. const id = document.getElementById('dhcp-server-modal-id').value;
  13466. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13467. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13468. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13469. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13470. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13471. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13472. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13473. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13474. try {
  13475. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13476. method: 'POST',
  13477. headers: { 'Content-Type': 'application/json' },
  13478. body: JSON.stringify({
  13479. id,
  13480. name,
  13481. interface: iface,
  13482. network,
  13483. address_pool: pool,
  13484. lease_time: leaseTime,
  13485. authoritative,
  13486. disabled,
  13487. comment
  13488. })
  13489. });
  13490. if (res.ok) {
  13491. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13492. closeDHCPServerModal();
  13493. loadDHCPServer(false);
  13494. fetchData(false);
  13495. } else {
  13496. const err = await res.text();
  13497. showToast('Error', err, 'error');
  13498. }
  13499. } catch (err) {
  13500. showToast('Error', err.message, 'error');
  13501. }
  13502. }
  13503. async function toggleDHCPServerState(id, disabled) {
  13504. try {
  13505. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13506. method: 'POST',
  13507. headers: { 'Content-Type': 'application/json' },
  13508. body: JSON.stringify({ disabled })
  13509. });
  13510. if (res.ok) {
  13511. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13512. loadDHCPServer(false);
  13513. fetchData(false);
  13514. }
  13515. } catch (err) {
  13516. showToast('Error', err.message, 'error');
  13517. }
  13518. }
  13519. async function deleteDHCPServer(id, name) {
  13520. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13521. try {
  13522. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13523. if (res.ok) {
  13524. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13525. loadDHCPServer(false);
  13526. fetchData(false);
  13527. }
  13528. } catch (err) {
  13529. showToast('Error', err.message, 'error');
  13530. }
  13531. }
  13532. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13533. function openAddDHCPNetworkModal() {
  13534. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13535. document.getElementById('dhcp-network-modal-id').value = '';
  13536. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13537. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13538. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13539. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13540. document.getElementById('dhcp-network-modal-netmask').value = '';
  13541. document.getElementById('dhcp-network-modal-comment').value = '';
  13542. renderDHCPNetworkOptionsCheckboxes([]);
  13543. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13544. }
  13545. function openEditDHCPNetworkModal(id) {
  13546. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13547. if (!n) return;
  13548. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13549. document.getElementById('dhcp-network-modal-id').value = n.id;
  13550. document.getElementById('dhcp-network-modal-address').value = n.address;
  13551. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13552. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13553. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13554. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13555. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13556. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13557. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13558. }
  13559. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13560. const container = document.getElementById('dhcp-network-modal-options-list');
  13561. if (!container) return;
  13562. container.innerHTML = '';
  13563. const opts = state.dhcpOptions || [];
  13564. if (opts.length === 0) {
  13565. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13566. return;
  13567. }
  13568. opts.forEach(o => {
  13569. const isChecked = selectedIds.includes(o.id);
  13570. const label = document.createElement('label');
  13571. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13572. label.innerHTML = `
  13573. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13574. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13575. `;
  13576. container.appendChild(label);
  13577. });
  13578. }
  13579. function closeDHCPNetworkModal() {
  13580. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13581. }
  13582. async function submitSaveDHCPNetwork(e) {
  13583. e.preventDefault();
  13584. const id = document.getElementById('dhcp-network-modal-id').value;
  13585. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13586. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13587. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13588. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13589. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13590. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13591. const selectedOpts = [];
  13592. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13593. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13594. try {
  13595. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13596. method: 'POST',
  13597. headers: { 'Content-Type': 'application/json' },
  13598. body: JSON.stringify({
  13599. id,
  13600. address,
  13601. gateway,
  13602. netmask,
  13603. dns_servers: dnsServers,
  13604. domain,
  13605. dhcp_options: selectedOpts,
  13606. comment
  13607. })
  13608. });
  13609. if (res.ok) {
  13610. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13611. closeDHCPNetworkModal();
  13612. loadDHCPServer(false);
  13613. fetchData(false);
  13614. } else {
  13615. const err = await res.text();
  13616. showToast('Error', err, 'error');
  13617. }
  13618. } catch (err) {
  13619. showToast('Error', err.message, 'error');
  13620. }
  13621. }
  13622. async function deleteDHCPNetwork(id, addr) {
  13623. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13624. try {
  13625. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13626. if (res.ok) {
  13627. showToast('Deleted', `Network ${addr} removed`, 'success');
  13628. loadDHCPServer(false);
  13629. fetchData(false);
  13630. }
  13631. } catch (err) {
  13632. showToast('Error', err.message, 'error');
  13633. }
  13634. }
  13635. // ==================== MODALS & ACTIONS: LEASES ====================
  13636. function openAddDHCPStaticLeaseModal() {
  13637. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13638. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13639. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13640. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13641. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13642. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13643. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13644. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13645. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13646. }
  13647. function closeDHCPStaticLeaseModal() {
  13648. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13649. }
  13650. async function submitSaveDHCPStaticLease(e) {
  13651. e.preventDefault();
  13652. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13653. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13654. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13655. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13656. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13657. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13658. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13659. try {
  13660. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13661. method: 'POST',
  13662. headers: { 'Content-Type': 'application/json' },
  13663. body: JSON.stringify({
  13664. id,
  13665. mac_address: mac,
  13666. address: ip,
  13667. hostname,
  13668. server,
  13669. comment,
  13670. disabled
  13671. })
  13672. });
  13673. if (res.ok) {
  13674. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13675. closeDHCPStaticLeaseModal();
  13676. loadDHCPServer(false);
  13677. fetchData(false);
  13678. } else {
  13679. const err = await res.text();
  13680. showToast('Error', err, 'error');
  13681. }
  13682. } catch (err) {
  13683. showToast('Error', err.message, 'error');
  13684. }
  13685. }
  13686. async function deleteDHCPStaticLease(id) {
  13687. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13688. try {
  13689. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13690. if (res.ok) {
  13691. showToast('Deleted', 'Static lease removed', 'success');
  13692. loadDHCPServer(false);
  13693. fetchData(false);
  13694. }
  13695. } catch (err) {
  13696. showToast('Error', err.message, 'error');
  13697. }
  13698. }
  13699. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13700. try {
  13701. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13702. method: 'POST',
  13703. headers: { 'Content-Type': 'application/json' },
  13704. body: JSON.stringify({
  13705. mac_address: mac,
  13706. address: ip,
  13707. hostname,
  13708. comment: comment || 'Converted to static'
  13709. })
  13710. });
  13711. if (res.ok) {
  13712. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13713. loadDHCPServer(false);
  13714. fetchData(false);
  13715. } else {
  13716. const err = await res.text();
  13717. showToast('Error', err, 'error');
  13718. }
  13719. } catch (err) {
  13720. showToast('Error', err.message, 'error');
  13721. }
  13722. }
  13723. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13724. function openAddDHCPOptionModal() {
  13725. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13726. document.getElementById('dhcp-option-modal-id').value = '';
  13727. document.getElementById('dhcp-option-modal-name').value = '';
  13728. document.getElementById('dhcp-option-modal-code').value = '';
  13729. document.getElementById('dhcp-option-modal-value').value = '';
  13730. document.getElementById('dhcp-option-modal-comment').value = '';
  13731. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13732. }
  13733. function openEditDHCPOptionModal(id) {
  13734. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13735. if (!o) return;
  13736. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13737. document.getElementById('dhcp-option-modal-id').value = o.id;
  13738. document.getElementById('dhcp-option-modal-name').value = o.name;
  13739. document.getElementById('dhcp-option-modal-code').value = o.code;
  13740. document.getElementById('dhcp-option-modal-value').value = o.value;
  13741. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13742. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13743. }
  13744. function closeDHCPOptionModal() {
  13745. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13746. }
  13747. async function submitSaveDHCPOption(e) {
  13748. e.preventDefault();
  13749. const id = document.getElementById('dhcp-option-modal-id').value;
  13750. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13751. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13752. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13753. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13754. try {
  13755. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13756. method: 'POST',
  13757. headers: { 'Content-Type': 'application/json' },
  13758. body: JSON.stringify({ id, name, code, value, comment })
  13759. });
  13760. if (res.ok) {
  13761. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13762. closeDHCPOptionModal();
  13763. loadDHCPServer(false);
  13764. fetchData(false);
  13765. } else {
  13766. const err = await res.text();
  13767. showToast('Error', err, 'error');
  13768. }
  13769. } catch (err) {
  13770. showToast('Error', err.message, 'error');
  13771. }
  13772. }
  13773. async function deleteDHCPOption(id, name) {
  13774. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13775. try {
  13776. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13777. if (res.ok) {
  13778. showToast('Deleted', `Option ${name} removed`, 'success');
  13779. loadDHCPServer(false);
  13780. fetchData(false);
  13781. }
  13782. } catch (err) {
  13783. showToast('Error', err.message, 'error');
  13784. }
  13785. }
  13786. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13787. function openDHCPServerSetupModal() {
  13788. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13789. onDHCPWizardIfaceChange();
  13790. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13791. }
  13792. function closeDHCPServerSetupModal() {
  13793. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13794. }
  13795. function onDHCPWizardIfaceChange() {
  13796. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13797. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13798. let ip = '192.168.88.1';
  13799. let prefix = '24';
  13800. if (iface && iface.ip_address) {
  13801. const parts = iface.ip_address.split('/');
  13802. ip = parts[0];
  13803. if (parts.length > 1) prefix = parts[1];
  13804. }
  13805. // Calculate subnet base (e.g. 192.168.88.0/24)
  13806. const ipParts = ip.split('.');
  13807. if (ipParts.length === 4) {
  13808. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13809. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13810. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13811. document.getElementById('dhcp-wizard-gateway').value = ip;
  13812. document.getElementById('dhcp-wizard-pool').value = pool;
  13813. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13814. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13815. }
  13816. }
  13817. async function submitDHCPServerSetupWizard(e) {
  13818. e.preventDefault();
  13819. const iface = document.getElementById('dhcp-wizard-iface').value;
  13820. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13821. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13822. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13823. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13824. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13825. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13826. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13827. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13828. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13829. try {
  13830. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13831. method: 'POST',
  13832. headers: { 'Content-Type': 'application/json' },
  13833. body: JSON.stringify({
  13834. interface: iface,
  13835. address_space: space,
  13836. gateway: gw,
  13837. address_pool: pool,
  13838. dns_servers: dnsServers,
  13839. lease_time: leaseTime,
  13840. ntp_servers: ntpServers,
  13841. next_server: tftp
  13842. })
  13843. });
  13844. if (res.ok) {
  13845. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13846. closeDHCPServerSetupModal();
  13847. loadDHCPServer(false);
  13848. fetchData(false);
  13849. } else {
  13850. const err = await res.text();
  13851. showToast('Error', err, 'error');
  13852. }
  13853. } catch (err) {
  13854. showToast('Error', err.message, 'error');
  13855. }
  13856. }
  13857. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13858. const sel = document.getElementById(elemId);
  13859. if (!sel) return;
  13860. sel.innerHTML = '<option value="">Select interface...</option>';
  13861. const ifaces = state.interfaces || [];
  13862. ifaces.forEach(i => {
  13863. if (i.name === 'lo') return;
  13864. const opt = document.createElement('option');
  13865. opt.value = i.name;
  13866. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13867. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13868. if (i.name === selectedVal) opt.selected = true;
  13869. sel.appendChild(opt);
  13870. });
  13871. }
  13872. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13873. function initTableSorting() {
  13874. document.querySelectorAll('table').forEach(setupSortableTable);
  13875. }
  13876. function setupSortableTable(table) {
  13877. const thead = table.querySelector('thead');
  13878. const tbody = table.querySelector('tbody');
  13879. if (!thead || !tbody) return;
  13880. const headerRows = thead.querySelectorAll('tr');
  13881. if (headerRows.length === 0) return;
  13882. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13883. ths.forEach((th, colIdx) => {
  13884. if (th._sortBound) return;
  13885. th._sortBound = true;
  13886. const rawText = th.innerText.trim().toLowerCase();
  13887. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13888. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13889. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13890. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13891. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13892. return;
  13893. }
  13894. th.classList.add('table-sortable', 'group');
  13895. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13896. let icon = th.querySelector('.table-sort-icon');
  13897. if (!icon) {
  13898. icon = document.createElement('span');
  13899. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13900. icon.innerHTML = '⇅';
  13901. th.appendChild(icon);
  13902. }
  13903. th.addEventListener('click', (e) => {
  13904. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13905. handleHeaderClick(table, th, colIdx);
  13906. });
  13907. });
  13908. if (!tbody._sortObserved) {
  13909. tbody._sortObserved = true;
  13910. let sortDebounceTimer = null;
  13911. const observer = new MutationObserver((mutations) => {
  13912. if (tbody._isSorting) return;
  13913. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13914. if (!hasChildChanges) return;
  13915. clearTimeout(sortDebounceTimer);
  13916. sortDebounceTimer = setTimeout(() => {
  13917. if (tbody._isSorting) return;
  13918. if (table._activeSort && table._activeSort.dir !== 'none') {
  13919. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13920. } else {
  13921. tagOriginalRowOrder(tbody);
  13922. }
  13923. }, 50);
  13924. });
  13925. tbody._sortObserver = observer;
  13926. observer.observe(tbody, { childList: true });
  13927. }
  13928. tagOriginalRowOrder(tbody);
  13929. }
  13930. function tagOriginalRowOrder(tbody) {
  13931. let idx = 0;
  13932. Array.from(tbody.children).forEach(tr => {
  13933. if (!tr.querySelector('td[colspan]')) {
  13934. if (!tr.hasAttribute('data-orig-idx')) {
  13935. tr.setAttribute('data-orig-idx', idx++);
  13936. }
  13937. }
  13938. });
  13939. }
  13940. function handleHeaderClick(table, th, colIdx) {
  13941. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13942. let newDir = 'asc';
  13943. if (currentSort.colIdx === colIdx) {
  13944. if (currentSort.dir === 'asc') newDir = 'desc';
  13945. else if (currentSort.dir === 'desc') newDir = 'none';
  13946. else newDir = 'asc';
  13947. } else {
  13948. newDir = 'asc';
  13949. }
  13950. table._activeSort = { colIdx, dir: newDir };
  13951. updateHeaderIcons(table, colIdx, newDir);
  13952. applyTableSort(table, colIdx, newDir, true);
  13953. }
  13954. function updateHeaderIcons(table, activeColIdx, dir) {
  13955. const thead = table.querySelector('thead');
  13956. if (!thead) return;
  13957. const ths = thead.querySelectorAll('th');
  13958. ths.forEach((th, idx) => {
  13959. const icon = th.querySelector('.table-sort-icon');
  13960. if (!icon) return;
  13961. if (idx === activeColIdx && dir !== 'none') {
  13962. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13963. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13964. th.classList.add('table-sorted-active');
  13965. } else {
  13966. icon.innerHTML = '⇅';
  13967. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13968. th.classList.remove('table-sorted-active');
  13969. }
  13970. });
  13971. }
  13972. function applyTableSort(table, colIdx, dir, userInitiated) {
  13973. const tbody = table.querySelector('tbody');
  13974. if (!tbody || tbody.children.length <= 1) return;
  13975. tbody._isSorting = true;
  13976. tagOriginalRowOrder(tbody);
  13977. // Group parent rows and any attached drawer/sub-rows
  13978. const groups = [];
  13979. let currentGroup = null;
  13980. Array.from(tbody.children).forEach(tr => {
  13981. if (tr.querySelector('td[colspan]')) {
  13982. if (currentGroup) {
  13983. currentGroup.subRows.push(tr);
  13984. } else {
  13985. groups.push({ mainRow: tr, subRows: [] });
  13986. }
  13987. } else {
  13988. currentGroup = { mainRow: tr, subRows: [] };
  13989. groups.push(currentGroup);
  13990. }
  13991. });
  13992. if (dir === 'none') {
  13993. groups.sort((a, b) => {
  13994. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13995. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13996. return idxA - idxB;
  13997. });
  13998. } else {
  13999. groups.sort((a, b) => {
  14000. const cellA = a.mainRow.children[colIdx];
  14001. const cellB = b.mainRow.children[colIdx];
  14002. const res = compareTableCells(cellA, cellB);
  14003. return dir === 'asc' ? res : -res;
  14004. });
  14005. }
  14006. // Check if rows are already in correct order to avoid modifying DOM
  14007. let alreadyOrdered = true;
  14008. let childIdx = 0;
  14009. for (const g of groups) {
  14010. if (tbody.children[childIdx] !== g.mainRow) {
  14011. alreadyOrdered = false;
  14012. break;
  14013. }
  14014. childIdx++;
  14015. for (const sub of g.subRows) {
  14016. if (tbody.children[childIdx] !== sub) {
  14017. alreadyOrdered = false;
  14018. break;
  14019. }
  14020. childIdx++;
  14021. }
  14022. }
  14023. if (alreadyOrdered) {
  14024. tbody._isSorting = false;
  14025. return;
  14026. }
  14027. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14028. if (tbody._sortObserver) {
  14029. tbody._sortObserver.disconnect();
  14030. }
  14031. // Re-append rows in sorted order
  14032. groups.forEach(g => {
  14033. tbody.appendChild(g.mainRow);
  14034. g.subRows.forEach(sub => tbody.appendChild(sub));
  14035. });
  14036. // Drain any queued mutations and re-connect observer
  14037. if (tbody._sortObserver) {
  14038. tbody._sortObserver.takeRecords();
  14039. tbody._sortObserver.observe(tbody, { childList: true });
  14040. }
  14041. tbody._isSorting = false;
  14042. }
  14043. function getCellRawText(cell) {
  14044. if (!cell) return '';
  14045. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14046. const input = cell.querySelector('input, select');
  14047. if (input) {
  14048. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14049. return input.value;
  14050. }
  14051. return cell.innerText.trim();
  14052. }
  14053. function parseTrafficToNumber(str) {
  14054. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14055. if (!m) return null;
  14056. const num = parseFloat(m[1].replace(/,/g, ''));
  14057. if (isNaN(num)) return null;
  14058. const unit = m[2].toUpperCase();
  14059. let mult = 1;
  14060. if (unit.startsWith('K')) mult = 1024;
  14061. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14062. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14063. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14064. return num * mult;
  14065. }
  14066. function parseIpToNumber(str) {
  14067. const clean = str.replace(/^[!~]/, '').trim();
  14068. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14069. if (!m) return null;
  14070. const o1 = parseInt(m[1], 10);
  14071. const o2 = parseInt(m[2], 10);
  14072. const o3 = parseInt(m[3], 10);
  14073. const o4 = parseInt(m[4], 10);
  14074. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14075. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14076. }
  14077. function parseCompoundPackets(str) {
  14078. const m = str.match(/^([\d,]+)p/);
  14079. if (!m) return null;
  14080. return parseInt(m[1].replace(/,/g, ''), 10);
  14081. }
  14082. function compareTableCells(cellA, cellB) {
  14083. const a = getCellRawText(cellA);
  14084. const b = getCellRawText(cellB);
  14085. if (a === '' && b !== '') return 1;
  14086. if (b === '' && a !== '') return -1;
  14087. if (a === b) return 0;
  14088. // 1. IP Addresses / CIDR
  14089. const ipA = parseIpToNumber(a);
  14090. const ipB = parseIpToNumber(b);
  14091. if (ipA !== null && ipB !== null) return ipA - ipB;
  14092. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14093. const pktA = parseCompoundPackets(a);
  14094. const pktB = parseCompoundPackets(b);
  14095. if (pktA !== null && pktB !== null) return pktA - pktB;
  14096. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14097. const trafA = parseTrafficToNumber(a);
  14098. const trafB = parseTrafficToNumber(b);
  14099. if (trafA !== null && trafB !== null) return trafA - trafB;
  14100. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14101. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14102. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14103. const numA = Number(cleanNumA);
  14104. const numB = Number(cleanNumB);
  14105. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14106. return numA - numB;
  14107. }
  14108. // 5. Natural case-insensitive string compare
  14109. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14110. }
  14111. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14112. async function loadVRRP(showToastNotification = false) {
  14113. try {
  14114. const [instRes, sumRes] = await Promise.all([
  14115. fetch(`${API_BASE}/vrrp/instances`),
  14116. fetch(`${API_BASE}/vrrp/summary`)
  14117. ]);
  14118. if (instRes.ok) {
  14119. state.vrrpInstances = await instRes.json();
  14120. renderVRRP();
  14121. }
  14122. if (sumRes.ok) {
  14123. state.vrrpSummary = await sumRes.json();
  14124. renderVRRPSummary();
  14125. }
  14126. if (showToastNotification) {
  14127. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14128. }
  14129. } catch (err) {
  14130. console.error('Failed to load VRRP:', err);
  14131. }
  14132. }
  14133. function renderVRRPSummary() {
  14134. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14135. const elTotal = document.getElementById('vrrp-stat-total');
  14136. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14137. const elMaster = document.getElementById('vrrp-stat-master');
  14138. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14139. const elBackup = document.getElementById('vrrp-stat-backup');
  14140. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14141. const bCount = document.getElementById('badge-vrrp-count');
  14142. if (bCount) bCount.innerText = s.total_instances || 0;
  14143. const dot = document.getElementById('badge-vrrp-dot');
  14144. if (dot) {
  14145. if (s.master_instances > 0) {
  14146. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14147. } else if (s.backup_instances > 0) {
  14148. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14149. } else {
  14150. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14151. }
  14152. }
  14153. }
  14154. function renderVRRP() {
  14155. const tbody = document.getElementById('vrrp-table-tbody');
  14156. const empty = document.getElementById('vrrp-table-empty');
  14157. if (!tbody) return;
  14158. tbody.innerHTML = '';
  14159. const instances = state.vrrpInstances || [];
  14160. if (instances.length === 0) {
  14161. empty?.classList.remove('hidden');
  14162. return;
  14163. }
  14164. empty?.classList.add('hidden');
  14165. instances.forEach(inst => {
  14166. const tr = document.createElement('tr');
  14167. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14168. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14169. 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>`;
  14170. if (inst.disabled) {
  14171. 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>`;
  14172. } else if (inst.state === 'MASTER') {
  14173. 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>`;
  14174. } else if (inst.state === 'BACKUP') {
  14175. 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>`;
  14176. } else if (inst.state === 'FAULT') {
  14177. 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>`;
  14178. }
  14179. // Render State Badge
  14180. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14181. if (!inst.disabled) {
  14182. if (inst.state === 'MASTER') {
  14183. 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>`;
  14184. } else if (inst.state === 'BACKUP') {
  14185. 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>`;
  14186. } else if (inst.state === 'FAULT') {
  14187. 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>`;
  14188. }
  14189. }
  14190. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14191. tr.innerHTML = `
  14192. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14193. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14194. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14195. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14196. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14197. <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>
  14198. <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>
  14199. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14200. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14201. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14202. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14203. <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>
  14204. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14205. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14206. </td>
  14207. `;
  14208. tbody.appendChild(tr);
  14209. });
  14210. }
  14211. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14212. const sel = document.getElementById(elemId);
  14213. if (!sel) return;
  14214. sel.innerHTML = '<option value="">Select interface...</option>';
  14215. const ifaces = state.interfaces || [];
  14216. ifaces.forEach(i => {
  14217. const opt = document.createElement('option');
  14218. opt.value = i.name;
  14219. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14220. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14221. sel.appendChild(opt);
  14222. });
  14223. }
  14224. function openAddVRRPModal() {
  14225. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14226. document.getElementById('modal-vrrp-id').value = '';
  14227. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14228. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14229. document.getElementById('modal-vrrp-priority').value = 100;
  14230. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14231. document.getElementById('modal-vrrp-version').value = '3';
  14232. document.getElementById('modal-vrrp-interval').value = 1;
  14233. document.getElementById('modal-vrrp-authtype').value = 'none';
  14234. document.getElementById('modal-vrrp-authpass').value = '';
  14235. document.getElementById('modal-vrrp-comment').value = '';
  14236. document.getElementById('modal-vrrp-preempt').checked = true;
  14237. document.getElementById('modal-vrrp-disabled').checked = false;
  14238. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14239. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14240. }
  14241. function openEditVRRPModal(id) {
  14242. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14243. if (!inst) return;
  14244. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14245. document.getElementById('modal-vrrp-id').value = inst.id;
  14246. document.getElementById('modal-vrrp-name').value = inst.name;
  14247. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14248. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14249. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14250. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14251. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14252. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14253. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14254. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14255. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14256. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14257. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14258. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14259. }
  14260. function closeVRRPModal() {
  14261. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14262. }
  14263. async function submitSaveVRRP(e) {
  14264. e.preventDefault();
  14265. const id = document.getElementById('modal-vrrp-id').value;
  14266. const name = document.getElementById('modal-vrrp-name').value.trim();
  14267. const iface = document.getElementById('modal-vrrp-iface').value;
  14268. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14269. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14270. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14271. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14272. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14273. const authType = document.getElementById('modal-vrrp-authtype').value;
  14274. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14275. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14276. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14277. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14278. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14279. try {
  14280. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14281. method: 'POST',
  14282. headers: { 'Content-Type': 'application/json' },
  14283. body: JSON.stringify({
  14284. id,
  14285. name,
  14286. interface: iface,
  14287. vrid,
  14288. priority,
  14289. virtual_ips: vips,
  14290. version,
  14291. interval,
  14292. auth_type: authType,
  14293. auth_password: authPass,
  14294. comment,
  14295. preempt,
  14296. disabled
  14297. })
  14298. });
  14299. if (res.ok) {
  14300. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14301. closeVRRPModal();
  14302. loadVRRP(false);
  14303. fetchData(false);
  14304. } else {
  14305. const err = await res.text();
  14306. showToast('Error', err, 'error');
  14307. }
  14308. } catch (err) {
  14309. showToast('Error', err.message, 'error');
  14310. }
  14311. }
  14312. async function deleteVRRP(id, name) {
  14313. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14314. try {
  14315. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14316. if (res.ok) {
  14317. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14318. loadVRRP(false);
  14319. fetchData(false);
  14320. } else {
  14321. const err = await res.text();
  14322. showToast('Error', err, 'error');
  14323. }
  14324. } catch (err) {
  14325. showToast('Error', err.message, 'error');
  14326. }
  14327. }
  14328. async function toggleVRRPState(id, disabled) {
  14329. try {
  14330. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14331. method: 'POST',
  14332. headers: { 'Content-Type': 'application/json' },
  14333. body: JSON.stringify({ disabled })
  14334. });
  14335. if (res.ok) {
  14336. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14337. loadVRRP(false);
  14338. fetchData(false);
  14339. } else {
  14340. const err = await res.text();
  14341. showToast('Error', err, 'error');
  14342. }
  14343. } catch (err) {
  14344. showToast('Error', err.message, 'error');
  14345. }
  14346. }
  14347. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14348. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14349. let docSortDebounce = null;
  14350. const docTableObserver = new MutationObserver((mutations) => {
  14351. let needsInit = false;
  14352. for (const m of mutations) {
  14353. for (const node of m.addedNodes) {
  14354. if (node.nodeType === 1) {
  14355. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14356. needsInit = true;
  14357. break;
  14358. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14359. needsInit = true;
  14360. break;
  14361. }
  14362. }
  14363. }
  14364. if (needsInit) break;
  14365. }
  14366. if (needsInit) {
  14367. clearTimeout(docSortDebounce);
  14368. docSortDebounce = setTimeout(initTableSorting, 100);
  14369. }
  14370. });
  14371. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14372. }
  14373. // =========================================================================
  14374. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14375. // =========================================================================
  14376. const bwtestState = {
  14377. running: false,
  14378. pollTimer: null,
  14379. eventSource: null,
  14380. chartPoints: [],
  14381. maxChartPoints: 60,
  14382. serverConfig: null,
  14383. peakTx: 0,
  14384. peakRx: 0,
  14385. targetDuration: 10,
  14386. lastSampleElapsed: -1,
  14387. sessionID: null
  14388. };
  14389. async function loadBwTestView() {
  14390. resizeBwTestCanvas();
  14391. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14392. }
  14393. async function fetchBwTestServerStatus() {
  14394. try {
  14395. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14396. if (!res.ok) return;
  14397. const s = await res.json();
  14398. bwtestState.serverConfig = s;
  14399. // Update indicator and badges
  14400. const indicator = document.getElementById('bwtest-server-indicator');
  14401. const badge = document.getElementById('bwtest-server-badge');
  14402. const sideBadge = document.getElementById('badge-bwtest-server');
  14403. if (s.enabled && s.running) {
  14404. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14405. if (badge) {
  14406. badge.innerText = `Port ${s.port} (Active)`;
  14407. badge.className = 'text-emerald-400 font-bold';
  14408. }
  14409. if (sideBadge) {
  14410. sideBadge.innerText = s.port;
  14411. 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';
  14412. }
  14413. } else {
  14414. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14415. if (badge) {
  14416. badge.innerText = `Disabled`;
  14417. badge.className = 'text-slate-500 font-bold';
  14418. }
  14419. if (sideBadge) {
  14420. sideBadge.innerText = 'Off';
  14421. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14422. }
  14423. }
  14424. // Modal fields
  14425. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14426. const serverModal = document.getElementById('modal-bwtest-server');
  14427. const editing = serverModal && !serverModal.classList.contains('hidden');
  14428. if (toggle && !editing) toggle.checked = !!s.enabled;
  14429. const portInp = document.getElementById('bwtest-server-port-input');
  14430. if (portInp && !editing) portInp.value = s.port || 2000;
  14431. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14432. if (actSess) actSess.innerText = s.active_sessions || 0;
  14433. const totServ = document.getElementById('bwtest-modal-total-served');
  14434. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14435. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14436. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14437. } catch (err) {
  14438. console.error('Failed to fetch BwTest server status:', err);
  14439. }
  14440. }
  14441. function openBwTestServerModal() {
  14442. const cfg = bwtestState.serverConfig;
  14443. if (cfg) {
  14444. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14445. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14446. }
  14447. fetchBwTestServerStatus();
  14448. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14449. }
  14450. function closeBwTestServerModal() {
  14451. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14452. }
  14453. async function submitBwTestServerSettings(e) {
  14454. e.preventDefault();
  14455. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14456. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14457. try {
  14458. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14459. method: 'POST',
  14460. headers: { 'Content-Type': 'application/json' },
  14461. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14462. });
  14463. if (!res.ok) {
  14464. const err = await res.json();
  14465. throw new Error(err.error || 'Failed to update server configuration');
  14466. }
  14467. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14468. closeBwTestServerModal();
  14469. fetchBwTestServerStatus();
  14470. } catch (err) {
  14471. showToast('Server Configuration Error', err.message, 'error');
  14472. }
  14473. }
  14474. function setBwTestTarget(target) {
  14475. const inp = document.getElementById('bwtest-input-target');
  14476. if (inp) inp.value = target;
  14477. }
  14478. function setBwTestProtocol(proto) {
  14479. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14480. if (hiddenInp) hiddenInp.value = proto;
  14481. const btnUdp = document.getElementById('bwtest-proto-udp');
  14482. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14483. const badge = document.getElementById('bwtest-proto-badge');
  14484. const pktField = document.getElementById('bwtest-field-pktsize');
  14485. 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';
  14486. 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';
  14487. 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';
  14488. if (proto === 'udp') {
  14489. if (btnUdp) {
  14490. btnUdp.className = activeUdpCls;
  14491. const dot = btnUdp.querySelector('span');
  14492. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14493. }
  14494. if (btnTcp) {
  14495. btnTcp.className = inactiveCls;
  14496. const dot = btnTcp.querySelector('span');
  14497. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14498. }
  14499. if (badge) {
  14500. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14501. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14502. }
  14503. if (pktField) pktField.classList.remove('opacity-40');
  14504. } else {
  14505. if (btnUdp) {
  14506. btnUdp.className = inactiveCls;
  14507. const dot = btnUdp.querySelector('span');
  14508. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14509. }
  14510. if (btnTcp) {
  14511. btnTcp.className = activeTcpCls;
  14512. const dot = btnTcp.querySelector('span');
  14513. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14514. }
  14515. if (badge) {
  14516. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14517. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14518. }
  14519. if (pktField) pktField.classList.add('opacity-40');
  14520. }
  14521. }
  14522. function setBwTestDirection(dir) {
  14523. const hiddenInp = document.getElementById('bwtest-input-direction');
  14524. if (hiddenInp) hiddenInp.value = dir;
  14525. const btnBoth = document.getElementById('bwtest-dir-both');
  14526. const btnTx = document.getElementById('bwtest-dir-tx');
  14527. const btnRx = document.getElementById('bwtest-dir-rx');
  14528. 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';
  14529. 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';
  14530. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14531. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14532. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14533. }
  14534. function setBwTestLimit(bps) {
  14535. const sel = document.getElementById('bwtest-input-limit');
  14536. if (sel) sel.value = String(bps);
  14537. }
  14538. async function checkActiveBwTest() {
  14539. try {
  14540. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14541. if (!res.ok) return;
  14542. const st = await res.json();
  14543. if (st.running) {
  14544. setBwTestRunningUI(true);
  14545. processBwTestStatus(st);
  14546. startBwTestTelemetry();
  14547. }
  14548. } catch (err) {
  14549. console.error('Failed to check active BwTest:', err);
  14550. }
  14551. }
  14552. async function startBwTest(e) {
  14553. if (e && e.preventDefault) e.preventDefault();
  14554. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14555. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14556. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14557. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14558. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14559. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14560. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14561. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14562. bwtestState.targetDuration = duration;
  14563. bwtestState.chartPoints = [];
  14564. bwtestState.peakTx = 0;
  14565. bwtestState.peakRx = 0;
  14566. bwtestState.lastSampleElapsed = -1;
  14567. bwtestState.sessionID = null;
  14568. // Clear UI elements
  14569. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14570. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14571. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14572. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14573. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14574. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14575. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14576. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14577. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14578. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14579. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14580. const tbody = document.getElementById('bwtest-samples-tbody');
  14581. if (tbody) tbody.innerHTML = '';
  14582. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14583. setBwTestRunningUI(true);
  14584. try {
  14585. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14586. method: 'POST',
  14587. headers: { 'Content-Type': 'application/json' },
  14588. body: JSON.stringify({
  14589. target,
  14590. port,
  14591. direction,
  14592. protocol,
  14593. bandwidth_limit,
  14594. packet_size,
  14595. streams,
  14596. duration
  14597. })
  14598. });
  14599. if (!res.ok) {
  14600. const err = await res.json();
  14601. throw new Error(err.error || 'Failed to start bandwidth test');
  14602. }
  14603. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14604. startBwTestTelemetry();
  14605. } catch (err) {
  14606. setBwTestRunningUI(false);
  14607. showToast('Start Failed', err.message, 'error');
  14608. }
  14609. }
  14610. function setBwTestRunningUI(running) {
  14611. bwtestState.running = running;
  14612. const startBtn = document.getElementById('bwtest-btn-start');
  14613. const stopBtn = document.getElementById('bwtest-btn-stop');
  14614. const badge = document.getElementById('bwtest-run-status-badge');
  14615. const ph = document.getElementById('bwtest-chart-placeholder');
  14616. if (running) {
  14617. if (startBtn) {
  14618. startBtn.disabled = true;
  14619. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14620. }
  14621. if (stopBtn) {
  14622. stopBtn.disabled = false;
  14623. stopBtn.classList.remove('opacity-40');
  14624. }
  14625. if (badge) {
  14626. badge.innerText = 'TESTING...';
  14627. 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';
  14628. }
  14629. if (ph) ph.style.display = 'none';
  14630. } else {
  14631. if (startBtn) {
  14632. startBtn.disabled = false;
  14633. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14634. }
  14635. if (stopBtn) {
  14636. stopBtn.disabled = true;
  14637. stopBtn.classList.add('opacity-40');
  14638. }
  14639. if (badge) {
  14640. badge.innerText = 'IDLE';
  14641. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14642. }
  14643. }
  14644. }
  14645. async function stopBwTest() {
  14646. try {
  14647. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14648. if (!res.ok) throw new Error(await responseError(res));
  14649. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14650. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14651. } catch (err) {
  14652. showToast('Stop Failed', err.message, 'error');
  14653. }
  14654. }
  14655. async function responseError(res) {
  14656. const text = await res.text();
  14657. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14658. catch { return text || `HTTP ${res.status}`; }
  14659. }
  14660. function processBwTestStatus(st) {
  14661. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14662. bwtestState.sessionID = st.session_id;
  14663. bwtestState.lastSampleElapsed = -1;
  14664. }
  14665. for (const sample of st.recent_samples || []) {
  14666. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14667. handleBwTestSample(sample);
  14668. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14669. }
  14670. }
  14671. if (!st.running) {
  14672. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14673. bwtestState.pollTimer = null;
  14674. setBwTestRunningUI(false);
  14675. handleBwTestFinish(st.summary, st.error);
  14676. }
  14677. }
  14678. function startBwTestTelemetry() {
  14679. if (!state.currentUser) return;
  14680. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14681. let busy = false;
  14682. const poll = async () => {
  14683. if (busy || !state.currentUser || document.hidden) return;
  14684. busy = true;
  14685. try {
  14686. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14687. if (!res.ok) throw new Error(await responseError(res));
  14688. processBwTestStatus(await res.json());
  14689. } catch (err) {
  14690. console.error('BwTest polling error:', err);
  14691. } finally { busy = false; }
  14692. };
  14693. bwtestState.pollTimer = setInterval(poll, 400);
  14694. poll();
  14695. }
  14696. function handleBwTestSample(s) {
  14697. if (!s) return;
  14698. const payloadHint = document.getElementById('bwtest-effective-payload');
  14699. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14700. const txMbps = s.tx_mbps || 0;
  14701. const rxMbps = s.rx_mbps || 0;
  14702. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14703. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14704. // KPI updates
  14705. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14706. if (elTx) {
  14707. elTx.innerText = txMbps.toFixed(2);
  14708. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14709. }
  14710. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14711. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14712. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14713. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14714. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14715. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14716. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14717. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14718. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14719. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14720. const elLoss = document.getElementById('bwtest-stat-loss');
  14721. if (elLoss) {
  14722. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14723. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14724. }
  14725. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14726. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14727. const elJitter = document.getElementById('bwtest-stat-jitter');
  14728. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14729. const elTime = document.getElementById('bwtest-stat-time');
  14730. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14731. const elData = document.getElementById('bwtest-stat-data');
  14732. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14733. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14734. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14735. // Append point to chart buffer
  14736. bwtestState.chartPoints.push({
  14737. elapsed: s.elapsed_sec || 0,
  14738. tx: txMbps,
  14739. rx: rxMbps
  14740. });
  14741. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14742. bwtestState.chartPoints.shift();
  14743. }
  14744. drawBwTestChart();
  14745. // Add row to breakdown table
  14746. const tbody = document.getElementById('bwtest-samples-tbody');
  14747. if (tbody) {
  14748. const tr = document.createElement('tr');
  14749. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14750. tr.innerHTML = `
  14751. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14752. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14753. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14754. <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>
  14755. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14756. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14757. `;
  14758. tbody.insertBefore(tr, tbody.firstChild);
  14759. const countEl = document.getElementById('bwtest-sample-count');
  14760. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14761. }
  14762. }
  14763. function handleBwTestFinish(summary, error) {
  14764. const badge = document.getElementById('bwtest-run-status-badge');
  14765. if (error) {
  14766. showToast('Benchmark Error', error, 'error');
  14767. if (badge) {
  14768. badge.innerText = 'ERROR';
  14769. 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';
  14770. }
  14771. } else if (summary) {
  14772. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14773. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14774. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14775. if (badge) {
  14776. badge.innerText = 'COMPLETED';
  14777. 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';
  14778. }
  14779. }
  14780. loadBwTestHistory();
  14781. fetchBwTestServerStatus();
  14782. }
  14783. function resizeBwTestCanvas() {
  14784. const canvas = document.getElementById('bwtest-chart');
  14785. if (!canvas || !canvas.parentElement) return;
  14786. const rect = canvas.parentElement.getBoundingClientRect();
  14787. const dpr = window.devicePixelRatio || 1;
  14788. canvas.width = rect.width * dpr;
  14789. canvas.height = rect.height * dpr;
  14790. const ctx = canvas.getContext('2d');
  14791. ctx.scale(dpr, dpr);
  14792. drawBwTestChart();
  14793. }
  14794. window.addEventListener('resize', () => {
  14795. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14796. });
  14797. function drawBwTestChart() {
  14798. const canvas = document.getElementById('bwtest-chart');
  14799. if (!canvas) return;
  14800. const ctx = canvas.getContext('2d');
  14801. const dpr = window.devicePixelRatio || 1;
  14802. const width = canvas.width / dpr;
  14803. const height = canvas.height / dpr;
  14804. ctx.clearRect(0, 0, width, height);
  14805. const points = bwtestState.chartPoints;
  14806. if (!points || points.length === 0) return;
  14807. // Determine scale ceiling
  14808. let maxRate = 10;
  14809. for (const p of points) {
  14810. if (p.tx > maxRate) maxRate = p.tx;
  14811. if (p.rx > maxRate) maxRate = p.rx;
  14812. }
  14813. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14814. const paddingLeft = 55;
  14815. const paddingBottom = 24;
  14816. const paddingTop = 12;
  14817. const paddingRight = 16;
  14818. const chartW = width - paddingLeft - paddingRight;
  14819. const chartH = height - paddingTop - paddingBottom;
  14820. // Grid Lines and Y-Axis labels
  14821. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14822. ctx.lineWidth = 1;
  14823. ctx.fillStyle = '#94a3b8';
  14824. ctx.font = '10px monospace';
  14825. ctx.textAlign = 'right';
  14826. const gridSteps = 4;
  14827. for (let i = 0; i <= gridSteps; i++) {
  14828. const val = (maxRate / gridSteps) * i;
  14829. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14830. ctx.beginPath();
  14831. ctx.moveTo(paddingLeft, y);
  14832. ctx.lineTo(width - paddingRight, y);
  14833. ctx.stroke();
  14834. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14835. }
  14836. // Draw TX Line (Cyan #22d3ee)
  14837. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14838. // Draw RX Line (Purple #a855f7)
  14839. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14840. }
  14841. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14842. if (points.length < 2) return;
  14843. const stepX = w / Math.max(points.length - 1, 1);
  14844. // Gradient area fill
  14845. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14846. grad.addColorStop(0, fillColor);
  14847. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14848. ctx.beginPath();
  14849. points.forEach((p, idx) => {
  14850. const x = left + idx * stepX;
  14851. const val = valFn(p);
  14852. const y = top + h - (val / maxVal) * h;
  14853. if (idx === 0) {
  14854. ctx.moveTo(x, y);
  14855. } else {
  14856. ctx.lineTo(x, y);
  14857. }
  14858. });
  14859. // Complete path for fill
  14860. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14861. ctx.lineTo(left, top + h);
  14862. ctx.closePath();
  14863. ctx.fillStyle = grad;
  14864. ctx.fill();
  14865. // Draw line stroke
  14866. ctx.beginPath();
  14867. ctx.lineWidth = 2.5;
  14868. ctx.strokeStyle = strokeColor;
  14869. points.forEach((p, idx) => {
  14870. const x = left + idx * stepX;
  14871. const val = valFn(p);
  14872. const y = top + h - (val / maxVal) * h;
  14873. if (idx === 0) {
  14874. ctx.moveTo(x, y);
  14875. } else {
  14876. ctx.lineTo(x, y);
  14877. }
  14878. });
  14879. ctx.stroke();
  14880. // Draw end point halo
  14881. const lastP = points[points.length - 1];
  14882. const lastX = left + (points.length - 1) * stepX;
  14883. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14884. ctx.fillStyle = strokeColor;
  14885. ctx.beginPath();
  14886. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14887. ctx.fill();
  14888. }
  14889. async function loadBwTestHistory() {
  14890. try {
  14891. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14892. if (!res.ok) return;
  14893. const list = await res.json();
  14894. renderBwTestHistory(Array.isArray(list) ? list : []);
  14895. } catch (err) {
  14896. console.error('Failed to load BwTest history:', err);
  14897. }
  14898. }
  14899. function renderBwTestHistory(list) {
  14900. const tbody = document.getElementById('bwtest-history-tbody');
  14901. if (!tbody) return;
  14902. if (list.length === 0) {
  14903. 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>`;
  14904. return;
  14905. }
  14906. tbody.innerHTML = '';
  14907. list.forEach(item => {
  14908. const s = item.summary || {};
  14909. const tr = document.createElement('tr');
  14910. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14911. const dirBadge = item.direction === 'both'
  14912. ? `<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>`
  14913. : item.direction === 'tx'
  14914. ? `<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>`
  14915. : `<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>`;
  14916. const protoBadge = item.protocol === 'tcp'
  14917. ? `<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>`
  14918. : `<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>`;
  14919. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14920. tr.innerHTML = `
  14921. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14922. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14923. <td class="py-2.5 px-4">${protoBadge}</td>
  14924. <td class="py-2.5 px-4">${dirBadge}</td>
  14925. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14926. <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>
  14927. <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>
  14928. <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>
  14929. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14930. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14931. `;
  14932. tbody.appendChild(tr);
  14933. });
  14934. }
  14935. // ======================== SETTINGS & ROUTER DNS ========================
  14936. state.settingsSubTab = 'dns';
  14937. state.dnsSettings = null;
  14938. state.dnsStaticRecords = [];
  14939. state.dnsStatus = null;
  14940. function switchSettingsSubTab(sub) {
  14941. state.settingsSubTab = sub;
  14942. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14943. const btnSys = document.getElementById('btn-settings-subtab-system');
  14944. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14945. const tabDns = document.getElementById('settings-subtab-dns');
  14946. const tabSys = document.getElementById('settings-subtab-system');
  14947. const tabBak = document.getElementById('settings-subtab-backup');
  14948. 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';
  14949. 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';
  14950. if (btnDns) btnDns.className = inactiveClass;
  14951. if (btnSys) btnSys.className = inactiveClass;
  14952. if (btnBak) btnBak.className = inactiveClass;
  14953. tabDns?.classList.add('hidden');
  14954. tabSys?.classList.add('hidden');
  14955. tabBak?.classList.add('hidden');
  14956. if (sub === 'dns') {
  14957. if (btnDns) btnDns.className = activeClass;
  14958. tabDns?.classList.remove('hidden');
  14959. loadDNSSettings();
  14960. } else if (sub === 'system') {
  14961. if (btnSys) btnSys.className = activeClass;
  14962. tabSys?.classList.remove('hidden');
  14963. loadSystemSettings();
  14964. } else if (sub === 'backup') {
  14965. if (btnBak) btnBak.className = activeClass;
  14966. tabBak?.classList.remove('hidden');
  14967. loadBackupList();
  14968. }
  14969. }
  14970. async function loadSettingsData(showLoading = false) {
  14971. if (state.settingsSubTab === 'system') {
  14972. await loadSystemSettings();
  14973. } else if (state.settingsSubTab === 'backup') {
  14974. await loadBackupList();
  14975. } else {
  14976. await loadDNSSettings();
  14977. }
  14978. }
  14979. async function loadDNSSettings() {
  14980. try {
  14981. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14982. fetch(`${API_BASE}/dns/settings`),
  14983. fetch(`${API_BASE}/dns/static`),
  14984. fetch(`${API_BASE}/dns/status`)
  14985. ]);
  14986. if (settingsRes.ok) {
  14987. state.dnsSettings = await settingsRes.json();
  14988. populateDNSSettingsForm(state.dnsSettings);
  14989. }
  14990. if (staticRes.ok) {
  14991. state.dnsStaticRecords = await staticRes.json();
  14992. renderStaticDNSList();
  14993. }
  14994. if (statusRes.ok) {
  14995. state.dnsStatus = await statusRes.json();
  14996. updateDNSStatusView(state.dnsStatus);
  14997. }
  14998. } catch (err) {
  14999. console.error('Failed to load DNS settings:', err);
  15000. }
  15001. }
  15002. function populateDNSSettingsForm(s) {
  15003. if (!s) return;
  15004. const dnsForm = document.getElementById('form-dns-settings');
  15005. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  15006. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  15007. if (dynamicEl) {
  15008. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  15009. 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(' ');
  15010. } else {
  15011. dynamicEl.innerText = 'None';
  15012. }
  15013. }
  15014. // If user is actively typing or editing in the form, do not overwrite their inputs!
  15015. if (isEditing) return;
  15016. const serversInput = document.getElementById('dns-servers-input');
  15017. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  15018. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  15019. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15020. const domainInput = document.getElementById('dns-domain-input');
  15021. if (domainInput) domainInput.value = s.domain || '';
  15022. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15023. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15024. }
  15025. function updateDNSStatusView(st) {
  15026. if (!st) return;
  15027. const preview = document.getElementById('dns-resolv-preview');
  15028. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15029. const pillText = document.getElementById('dns-live-status-text');
  15030. const pill = document.getElementById('dns-live-status-pill');
  15031. if (pill && pillText) {
  15032. if (st.service_running) {
  15033. 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';
  15034. pillText.innerText = 'DNS Service Active';
  15035. } else {
  15036. 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';
  15037. pillText.innerText = 'DNS Service Inactive';
  15038. }
  15039. }
  15040. }
  15041. function appendDNSPreset(preset) {
  15042. const input = document.getElementById('dns-servers-input');
  15043. if (!input) return;
  15044. const dnsForm = document.getElementById('form-dns-settings');
  15045. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15046. const current = input.value.trim();
  15047. if (!current) {
  15048. input.value = preset;
  15049. } else {
  15050. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15051. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15052. toAdd.forEach(ip => {
  15053. if (!existing.includes(ip)) existing.push(ip);
  15054. });
  15055. input.value = existing.join(', ');
  15056. }
  15057. }
  15058. async function saveDNSSettings(e) {
  15059. e.preventDefault();
  15060. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15061. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15062. if (servers.length === 0) {
  15063. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15064. return;
  15065. }
  15066. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15067. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15068. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15069. try {
  15070. const res = await fetch(`${API_BASE}/dns/settings`, {
  15071. method: 'POST',
  15072. headers: { 'Content-Type': 'application/json' },
  15073. body: JSON.stringify({
  15074. servers: servers,
  15075. cache_size: cacheSize,
  15076. domain: domain,
  15077. allow_remote_requests: allowRemote
  15078. })
  15079. });
  15080. const data = await res.json();
  15081. if (res.ok) {
  15082. const dnsForm = document.getElementById('form-dns-settings');
  15083. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15084. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15085. loadDNSSettings();
  15086. } else {
  15087. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15088. }
  15089. } catch (err) {
  15090. showToast('Error', err.message, 'error');
  15091. }
  15092. }
  15093. async function flushDNSCache() {
  15094. try {
  15095. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15096. if (res.ok) {
  15097. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15098. loadDNSSettings();
  15099. } else {
  15100. const err = await res.json();
  15101. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15102. }
  15103. } catch (err) {
  15104. showToast('Error', err.message, 'error');
  15105. }
  15106. }
  15107. function renderStaticDNSList() {
  15108. const tbody = document.getElementById('dns-static-tbody');
  15109. const empty = document.getElementById('dns-static-empty');
  15110. const badge = document.getElementById('dns-static-count-badge');
  15111. if (!tbody) return;
  15112. tbody.innerHTML = '';
  15113. const records = state.dnsStaticRecords || [];
  15114. if (badge) badge.innerText = `${records.length} Records`;
  15115. if (records.length === 0) {
  15116. empty?.classList.remove('hidden');
  15117. return;
  15118. }
  15119. empty?.classList.add('hidden');
  15120. records.forEach(rec => {
  15121. const tr = document.createElement('tr');
  15122. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15123. tr.innerHTML = `
  15124. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15125. <td class="py-2.5 px-4">
  15126. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15127. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15128. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15129. }">
  15130. ${rec.type || 'A'}
  15131. </span>
  15132. </td>
  15133. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15134. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15135. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15136. <td class="py-2.5 px-4">
  15137. <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'}">
  15138. ${rec.disabled ? 'Disabled' : 'Active'}
  15139. </span>
  15140. </td>
  15141. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15142. <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>
  15143. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15144. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15145. </td>
  15146. `;
  15147. tbody.appendChild(tr);
  15148. });
  15149. }
  15150. function openStaticDNSModal(id = null) {
  15151. const modal = document.getElementById('modal-static-dns');
  15152. const title = document.getElementById('modal-static-dns-title');
  15153. const form = document.getElementById('form-static-dns');
  15154. if (!modal || !form) return;
  15155. form.reset();
  15156. document.getElementById('modal-static-dns-id').value = '';
  15157. if (id) {
  15158. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15159. if (rec) {
  15160. if (title) title.innerText = 'Edit Static DNS Record';
  15161. document.getElementById('modal-static-dns-id').value = rec.id;
  15162. document.getElementById('modal-static-dns-name').value = rec.name;
  15163. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15164. document.getElementById('modal-static-dns-addr').value = rec.address;
  15165. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15166. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15167. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15168. }
  15169. } else {
  15170. if (title) title.innerText = 'Add Static DNS Record';
  15171. }
  15172. modal.classList.remove('hidden');
  15173. }
  15174. function closeStaticDNSModal() {
  15175. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15176. }
  15177. async function submitSaveStaticDNS(e) {
  15178. e.preventDefault();
  15179. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15180. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15181. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15182. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15183. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15184. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15185. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15186. if (!name || !address) {
  15187. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15188. return;
  15189. }
  15190. try {
  15191. const res = await fetch(`${API_BASE}/dns/static`, {
  15192. method: 'POST',
  15193. headers: { 'Content-Type': 'application/json' },
  15194. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15195. });
  15196. const data = await res.json();
  15197. if (res.ok) {
  15198. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15199. closeStaticDNSModal();
  15200. loadDNSSettings();
  15201. } else {
  15202. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15203. }
  15204. } catch (err) {
  15205. showToast('Error', err.message, 'error');
  15206. }
  15207. }
  15208. async function deleteStaticDNS(id) {
  15209. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15210. try {
  15211. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15212. if (res.ok) {
  15213. showToast('Deleted', 'Static DNS record deleted', 'success');
  15214. loadDNSSettings();
  15215. }
  15216. } catch (err) {
  15217. showToast('Error', err.message, 'error');
  15218. }
  15219. }
  15220. async function toggleStaticDNS(id, disabled) {
  15221. try {
  15222. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15223. method: 'POST',
  15224. headers: { 'Content-Type': 'application/json' },
  15225. body: JSON.stringify({ disabled })
  15226. });
  15227. if (res.ok) {
  15228. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15229. loadDNSSettings();
  15230. }
  15231. } catch (err) {
  15232. showToast('Error', err.message, 'error');
  15233. }
  15234. }
  15235. async function loadSystemSettings() {
  15236. try {
  15237. const sysForm = document.getElementById('form-system-settings');
  15238. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15239. const res = await fetch(`${API_BASE}/system/settings`);
  15240. if (res.ok) {
  15241. const data = await res.json();
  15242. if (!isEditing) {
  15243. const hostInput = document.getElementById('system-hostname-input');
  15244. if (hostInput) hostInput.value = data.hostname || '';
  15245. const tzInput = document.getElementById('system-timezone-input');
  15246. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15247. }
  15248. }
  15249. } catch (err) {
  15250. console.error('Failed to load system settings:', err);
  15251. }
  15252. }
  15253. async function saveSystemSettings(e) {
  15254. e.preventDefault();
  15255. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15256. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15257. try {
  15258. const res = await fetch(`${API_BASE}/system/settings`, {
  15259. method: 'POST',
  15260. headers: { 'Content-Type': 'application/json' },
  15261. body: JSON.stringify({ hostname, timezone })
  15262. });
  15263. const data = await res.json();
  15264. if (res.ok) {
  15265. const sysForm = document.getElementById('form-system-settings');
  15266. if (sysForm) sysForm.dataset.dirty = 'false';
  15267. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15268. const sideH = document.getElementById('side-hostname');
  15269. if (sideH) sideH.innerText = data.hostname;
  15270. } else {
  15271. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15272. }
  15273. } catch (err) {
  15274. showToast('Error', err.message, 'error');
  15275. }
  15276. }
  15277. // =============================================================================
  15278. // BACKUP & RESTORE MANAGER
  15279. // =============================================================================
  15280. state.selectedBackupFile = null;
  15281. state.inspectedBackupManifest = null;
  15282. state.pendingRestoreTarget = null;
  15283. state.backupsList = [];
  15284. async function exportBackupDownload() {
  15285. const btn = document.getElementById('btn-export-backup');
  15286. const commentInput = document.getElementById('backup-export-comment');
  15287. const comment = (commentInput?.value || '').trim();
  15288. const originalHtml = btn ? btn.innerHTML : '';
  15289. if (btn) {
  15290. btn.disabled = true;
  15291. 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...`;
  15292. }
  15293. try {
  15294. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15295. if (!res.ok) {
  15296. const err = await res.json().catch(() => ({}));
  15297. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15298. return;
  15299. }
  15300. const blob = await res.blob();
  15301. const disposition = res.headers.get('Content-Disposition') || '';
  15302. let filename = 'debtik-backup.zip';
  15303. const match = disposition.match(/filename="?([^";]+)"?/);
  15304. if (match && match[1]) {
  15305. filename = match[1];
  15306. }
  15307. const blobUrl = window.URL.createObjectURL(blob);
  15308. const a = document.createElement('a');
  15309. a.href = blobUrl;
  15310. a.download = filename;
  15311. document.body.appendChild(a);
  15312. a.click();
  15313. setTimeout(() => {
  15314. window.URL.revokeObjectURL(blobUrl);
  15315. a.remove();
  15316. }, 1000);
  15317. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15318. } catch (err) {
  15319. showToast('Export Error', err.message || 'Network error during download', 'error');
  15320. } finally {
  15321. if (btn) {
  15322. btn.disabled = false;
  15323. btn.innerHTML = originalHtml;
  15324. }
  15325. }
  15326. }
  15327. async function onBackupFileSelected(e) {
  15328. const file = e.target.files?.[0];
  15329. if (!file) return;
  15330. const label = document.getElementById('backup-file-label');
  15331. if (label) {
  15332. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15333. }
  15334. await inspectBackupFile(file);
  15335. }
  15336. async function inspectBackupFile(file) {
  15337. const preview = document.getElementById('backup-inspect-preview');
  15338. const restoreBtn = document.getElementById('btn-restore-backup');
  15339. const formData = new FormData();
  15340. formData.append('backup', file);
  15341. try {
  15342. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15343. method: 'POST',
  15344. body: formData
  15345. });
  15346. const data = await res.json();
  15347. if (!res.ok || !data.success || !data.manifest) {
  15348. if (preview) preview.classList.add('hidden');
  15349. if (restoreBtn) restoreBtn.disabled = true;
  15350. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15351. return;
  15352. }
  15353. const mf = data.manifest;
  15354. state.selectedBackupFile = file;
  15355. state.inspectedBackupManifest = mf;
  15356. const vEl = document.getElementById('backup-inspect-version');
  15357. const hEl = document.getElementById('backup-inspect-hostname');
  15358. const fEl = document.getElementById('backup-inspect-files');
  15359. const dEl = document.getElementById('backup-inspect-date');
  15360. const cEl = document.getElementById('backup-inspect-comment');
  15361. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15362. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15363. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15364. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15365. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15366. if (preview) preview.classList.remove('hidden');
  15367. if (restoreBtn) restoreBtn.disabled = false;
  15368. } catch (err) {
  15369. if (preview) preview.classList.add('hidden');
  15370. if (restoreBtn) restoreBtn.disabled = true;
  15371. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15372. }
  15373. }
  15374. function confirmRestoreBackup(localFilename = null) {
  15375. const modal = document.getElementById('modal-restore-confirm');
  15376. const details = document.getElementById('modal-restore-details');
  15377. const progress = document.getElementById('modal-restore-progress');
  15378. const cancelBtn = document.getElementById('btn-cancel-restore');
  15379. const execBtn = document.getElementById('btn-execute-restore');
  15380. if (progress) progress.classList.add('hidden');
  15381. if (cancelBtn) cancelBtn.disabled = false;
  15382. if (execBtn) {
  15383. execBtn.disabled = false;
  15384. execBtn.innerText = 'Yes, Restore & Reload';
  15385. }
  15386. if (localFilename) {
  15387. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15388. if (details) {
  15389. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15390. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15391. }
  15392. } else {
  15393. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15394. showToast('Error', 'Please select a valid backup archive first', 'error');
  15395. return;
  15396. }
  15397. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15398. const mf = state.inspectedBackupManifest;
  15399. if (details) {
  15400. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15401. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15402. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15403. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15404. }
  15405. }
  15406. if (modal) modal.classList.remove('hidden');
  15407. }
  15408. function closeRestoreModal() {
  15409. const modal = document.getElementById('modal-restore-confirm');
  15410. if (modal) modal.classList.add('hidden');
  15411. }
  15412. async function executeRestoreBackup() {
  15413. const target = state.pendingRestoreTarget;
  15414. if (!target) return;
  15415. const progress = document.getElementById('modal-restore-progress');
  15416. const progressText = document.getElementById('modal-restore-progress-text');
  15417. const cancelBtn = document.getElementById('btn-cancel-restore');
  15418. const execBtn = document.getElementById('btn-execute-restore');
  15419. if (cancelBtn) cancelBtn.disabled = true;
  15420. if (execBtn) execBtn.disabled = true;
  15421. if (progress) progress.classList.remove('hidden');
  15422. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15423. try {
  15424. let res;
  15425. if (target.type === 'file') {
  15426. const formData = new FormData();
  15427. formData.append('backup', target.file);
  15428. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15429. method: 'POST',
  15430. body: formData
  15431. });
  15432. } else {
  15433. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15434. method: 'POST'
  15435. });
  15436. }
  15437. const data = await res.json();
  15438. if (!res.ok || !data.success) {
  15439. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15440. if (cancelBtn) cancelBtn.disabled = false;
  15441. if (execBtn) execBtn.disabled = false;
  15442. if (progress) progress.classList.add('hidden');
  15443. return;
  15444. }
  15445. if (progressText) {
  15446. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15447. }
  15448. pollAfterRestoreReconnect();
  15449. } catch (err) {
  15450. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15451. if (cancelBtn) cancelBtn.disabled = false;
  15452. if (execBtn) execBtn.disabled = false;
  15453. if (progress) progress.classList.add('hidden');
  15454. }
  15455. }
  15456. function pollAfterRestoreReconnect() {
  15457. let attempts = 0;
  15458. const maxAttempts = 25;
  15459. const timer = setInterval(async () => {
  15460. attempts++;
  15461. try {
  15462. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15463. if (res.ok) {
  15464. clearInterval(timer);
  15465. closeRestoreModal();
  15466. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15467. setTimeout(() => {
  15468. window.location.reload();
  15469. }, 1200);
  15470. }
  15471. } catch (_) {
  15472. // Still restarting, retry
  15473. }
  15474. if (attempts >= maxAttempts) {
  15475. clearInterval(timer);
  15476. closeRestoreModal();
  15477. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15478. }
  15479. }, 1500);
  15480. }
  15481. async function loadBackupList() {
  15482. const tbody = document.getElementById('backups-table-tbody');
  15483. const empty = document.getElementById('backups-empty-state');
  15484. if (!tbody) return;
  15485. try {
  15486. const res = await fetch(`${API_BASE}/system/backups`);
  15487. if (!res.ok) return;
  15488. const list = await res.json();
  15489. state.backupsList = list || [];
  15490. renderBackupsTable(state.backupsList);
  15491. } catch (err) {
  15492. console.error('Failed to load backup list:', err);
  15493. }
  15494. }
  15495. function renderBackupsTable(backups) {
  15496. const tbody = document.getElementById('backups-table-tbody');
  15497. const empty = document.getElementById('backups-empty-state');
  15498. if (!tbody) return;
  15499. if (!backups || backups.length === 0) {
  15500. tbody.innerHTML = '';
  15501. if (empty) empty.classList.remove('hidden');
  15502. return;
  15503. }
  15504. if (empty) empty.classList.add('hidden');
  15505. tbody.innerHTML = backups.map(bk => {
  15506. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15507. const badge = isAuto
  15508. ? `<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>`
  15509. : `<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>`;
  15510. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15511. return `<tr class="hover:bg-slate-800/40 transition">
  15512. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15513. ${badge}
  15514. <span>${escapeHtml(bk.filename)}</span>
  15515. </td>
  15516. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15517. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15518. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15519. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15520. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15521. <td class="py-3 px-4 text-right space-x-2">
  15522. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15523. 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">
  15524. Download
  15525. </button>
  15526. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15527. 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">
  15528. Restore
  15529. </button>
  15530. </td>
  15531. </tr>`;
  15532. }).join('');
  15533. }
  15534. async function downloadLocalBackup(filename) {
  15535. try {
  15536. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15537. if (!res.ok) {
  15538. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15539. return;
  15540. }
  15541. const blob = await res.blob();
  15542. const blobUrl = window.URL.createObjectURL(blob);
  15543. const a = document.createElement('a');
  15544. a.href = blobUrl;
  15545. a.download = filename;
  15546. document.body.appendChild(a);
  15547. a.click();
  15548. setTimeout(() => {
  15549. window.URL.revokeObjectURL(blobUrl);
  15550. a.remove();
  15551. }, 1000);
  15552. } catch (err) {
  15553. showToast('Download Error', err.message, 'error');
  15554. }
  15555. }
  15556. // =============================================================================
  15557. // AUTHENTICATION & USER MANAGER
  15558. // =============================================================================
  15559. async function checkAuthStatus() {
  15560. try {
  15561. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15562. headers: {
  15563. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15564. }
  15565. });
  15566. if (res.ok) {
  15567. const user = await res.json();
  15568. state.currentUser = user;
  15569. updateUserProfileHeader(user);
  15570. hideLoginScreen();
  15571. state.isPolling = true;
  15572. fetchData();
  15573. initLiveTrafficStream();
  15574. return true;
  15575. } else {
  15576. showLoginScreen(false);
  15577. return false;
  15578. }
  15579. } catch (err) {
  15580. showLoginScreen(false);
  15581. return false;
  15582. }
  15583. }
  15584. function showLoginScreen(isExpired = false) {
  15585. const el = document.getElementById('login-screen');
  15586. if (el) el.classList.remove('hidden');
  15587. const errEl = document.getElementById('login-error');
  15588. const errTxt = document.getElementById('login-error-text');
  15589. if (isExpired && errEl && errTxt) {
  15590. errTxt.innerText = 'Session expired. Please sign in again.';
  15591. errEl.classList.remove('hidden');
  15592. } else if (errEl) {
  15593. errEl.classList.add('hidden');
  15594. }
  15595. const pwInput = document.getElementById('login-password');
  15596. if (pwInput) pwInput.value = '';
  15597. const userInput = document.getElementById('login-username');
  15598. if (userInput && !userInput.value) userInput.focus();
  15599. else if (pwInput) pwInput.focus();
  15600. }
  15601. function hideLoginScreen() {
  15602. const el = document.getElementById('login-screen');
  15603. if (el) el.classList.add('hidden');
  15604. const errEl = document.getElementById('login-error');
  15605. if (errEl) errEl.classList.add('hidden');
  15606. }
  15607. async function handleLoginSubmit(event) {
  15608. event.preventDefault();
  15609. const username = (document.getElementById('login-username')?.value || '').trim();
  15610. const password = document.getElementById('login-password')?.value || '';
  15611. const errEl = document.getElementById('login-error');
  15612. const errTxt = document.getElementById('login-error-text');
  15613. const btn = document.getElementById('login-submit-btn');
  15614. const btnText = document.getElementById('login-btn-text');
  15615. const spinner = document.getElementById('login-btn-spinner');
  15616. if (!username || !password) {
  15617. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15618. if (errEl) errEl.classList.remove('hidden');
  15619. return;
  15620. }
  15621. if (errEl) errEl.classList.add('hidden');
  15622. if (btn) btn.disabled = true;
  15623. if (btnText) btnText.innerText = 'Authenticating...';
  15624. if (spinner) spinner.classList.remove('hidden');
  15625. try {
  15626. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15627. method: 'POST',
  15628. headers: { 'Content-Type': 'application/json' },
  15629. body: JSON.stringify({ username, password })
  15630. });
  15631. const data = await res.json();
  15632. if (res.ok && data.success) {
  15633. localStorage.setItem('debtik_token', data.token);
  15634. state.currentUser = data.user;
  15635. updateUserProfileHeader(data.user);
  15636. hideLoginScreen();
  15637. state.isPolling = true;
  15638. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15639. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15640. navigate(hash);
  15641. fetchData();
  15642. initLiveTrafficStream();
  15643. // Ensure background telemetry polling is active
  15644. if (!window._telemetryInterval) {
  15645. window._telemetryInterval = setInterval(() => {
  15646. if (state.isPolling && state.currentUser && !document.hidden) {
  15647. fetchData(false);
  15648. }
  15649. }, 5000);
  15650. }
  15651. } else {
  15652. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15653. if (errEl) errEl.classList.remove('hidden');
  15654. }
  15655. } catch (err) {
  15656. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15657. if (errEl) errEl.classList.remove('hidden');
  15658. } finally {
  15659. if (btn) btn.disabled = false;
  15660. if (btnText) btnText.innerText = 'Sign In to Controller';
  15661. if (spinner) spinner.classList.add('hidden');
  15662. }
  15663. }
  15664. async function handleLogoutClick() {
  15665. try {
  15666. await originalFetch(`${API_BASE}/auth/logout`, {
  15667. method: 'POST',
  15668. headers: {
  15669. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15670. }
  15671. });
  15672. } catch (e) {}
  15673. stopSessionPolling();
  15674. localStorage.removeItem('debtik_token');
  15675. state.currentUser = null;
  15676. state.isPolling = false;
  15677. if (window._telemetryInterval) {
  15678. clearInterval(window._telemetryInterval);
  15679. window._telemetryInterval = null;
  15680. }
  15681. if (trafficEventSource) {
  15682. trafficEventSource.close();
  15683. trafficEventSource = null;
  15684. }
  15685. if (trafficPollFallback) {
  15686. clearInterval(trafficPollFallback);
  15687. trafficPollFallback = null;
  15688. }
  15689. showLoginScreen(false);
  15690. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15691. }
  15692. function togglePasswordVisibility(id) {
  15693. const input = document.getElementById(id);
  15694. if (!input) return;
  15695. input.type = input.type === 'password' ? 'text' : 'password';
  15696. }
  15697. function toggleUserMenu() {
  15698. const menu = document.getElementById('user-menu-dropdown');
  15699. if (menu) menu.classList.toggle('hidden');
  15700. }
  15701. function closeUserMenu() {
  15702. const menu = document.getElementById('user-menu-dropdown');
  15703. if (menu) menu.classList.add('hidden');
  15704. }
  15705. // Close user menu on outside click
  15706. document.addEventListener('click', (e) => {
  15707. const menu = document.getElementById('user-menu-dropdown');
  15708. if (!menu || menu.classList.contains('hidden')) return;
  15709. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15710. menu.classList.add('hidden');
  15711. }
  15712. });
  15713. function updateUserProfileHeader(user) {
  15714. if (!user) return;
  15715. const navName = document.getElementById('nav-user-name');
  15716. if (navName) navName.innerText = user.username;
  15717. const dropName = document.getElementById('dropdown-user-name');
  15718. if (dropName) dropName.innerText = user.username;
  15719. const navRole = document.getElementById('nav-user-role');
  15720. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15721. const navAvatar = document.getElementById('nav-user-avatar');
  15722. if (navAvatar) {
  15723. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15724. navAvatar.innerText = initials;
  15725. }
  15726. const statCurUser = document.getElementById('stat-current-user');
  15727. if (statCurUser) statCurUser.innerText = user.username;
  15728. const statCurRole = document.getElementById('stat-current-role');
  15729. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15730. // Role permissions UI visibility: hide user management for non-admins
  15731. const isFullAdmin = user.role === 'full';
  15732. const navUsers = document.getElementById('nav-users');
  15733. if (navUsers) {
  15734. if (isFullAdmin) navUsers.classList.remove('hidden');
  15735. else navUsers.classList.add('hidden');
  15736. }
  15737. const dropdownUsers = document.getElementById('dropdown-item-users');
  15738. if (dropdownUsers) {
  15739. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15740. else dropdownUsers.classList.add('hidden');
  15741. }
  15742. }
  15743. // ================= User Management CRUD =================
  15744. async function loadUsers(isManual = false) {
  15745. try {
  15746. const res = await fetch(`${API_BASE}/users`);
  15747. if (res.status === 403) {
  15748. const tbody = document.getElementById('users-table-tbody');
  15749. if (tbody) {
  15750. tbody.innerHTML = `
  15751. <tr>
  15752. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15753. <div class="inline-flex items-center gap-2">
  15754. <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>
  15755. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15756. </div>
  15757. </td>
  15758. </tr>
  15759. `;
  15760. }
  15761. return;
  15762. }
  15763. if (res.ok) {
  15764. state.users = await res.json();
  15765. renderUsersTable();
  15766. const totalUsers = document.getElementById('stat-total-users');
  15767. if (totalUsers) totalUsers.innerText = state.users.length;
  15768. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15769. const adminUsers = document.getElementById('stat-admin-users');
  15770. if (adminUsers) adminUsers.innerText = adminCount;
  15771. const badgeCount = document.getElementById('badge-users-count');
  15772. if (badgeCount) badgeCount.innerText = state.users.length;
  15773. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15774. }
  15775. } catch (err) {
  15776. console.error('Failed to load users:', err);
  15777. }
  15778. }
  15779. function renderUsersTable() {
  15780. const tbody = document.getElementById('users-table-tbody');
  15781. const emptyState = document.getElementById('users-empty-state');
  15782. if (!tbody) return;
  15783. tbody.innerHTML = '';
  15784. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15785. const filtered = (state.users || []).filter(u => {
  15786. if (!query) return true;
  15787. return u.username.toLowerCase().includes(query) ||
  15788. (u.role || '').toLowerCase().includes(query) ||
  15789. (u.comment || '').toLowerCase().includes(query);
  15790. });
  15791. if (filtered.length === 0) {
  15792. if (emptyState) emptyState.classList.remove('hidden');
  15793. return;
  15794. }
  15795. if (emptyState) emptyState.classList.add('hidden');
  15796. const currentAuthUser = state.currentUser?.username || '';
  15797. filtered.forEach(u => {
  15798. const isSelf = u.username === currentAuthUser;
  15799. const isFull = u.role === 'full';
  15800. const isWrite = u.role === 'write';
  15801. 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>`;
  15802. if (isFull) {
  15803. 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>`;
  15804. } else if (isWrite) {
  15805. 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>`;
  15806. }
  15807. const statusBadge = u.disabled
  15808. ? `<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>`
  15809. : `<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>`;
  15810. let lastLoginText = 'Never';
  15811. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15812. const dt = new Date(u.last_login_at);
  15813. lastLoginText = dt.toLocaleString();
  15814. }
  15815. const initials = u.username.slice(0, 2).toUpperCase();
  15816. const tr = document.createElement('tr');
  15817. tr.className = 'hover:bg-slate-800/40 transition group';
  15818. tr.innerHTML = `
  15819. <td class="py-3 px-4">
  15820. <div class="flex items-center gap-3">
  15821. <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">
  15822. ${initials}
  15823. </div>
  15824. <div>
  15825. <div class="font-bold text-white text-xs flex items-center gap-2">
  15826. <span>${escapeHtml(u.username)}</span>
  15827. ${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>' : ''}
  15828. </div>
  15829. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15830. </div>
  15831. </div>
  15832. </td>
  15833. <td class="py-3 px-4 font-sans">
  15834. ${roleBadge}
  15835. </td>
  15836. <td class="py-3 px-4 font-sans">
  15837. ${statusBadge}
  15838. </td>
  15839. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15840. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15841. </td>
  15842. <td class="py-3 px-4 text-slate-400 text-xs">
  15843. ${lastLoginText}
  15844. </td>
  15845. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15846. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15847. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15848. <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>
  15849. </button>
  15850. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15851. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15852. <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>
  15853. </button>
  15854. ${!isSelf ? `
  15855. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15856. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15857. <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>
  15858. </button>
  15859. ` : ''}
  15860. </td>
  15861. `;
  15862. tbody.appendChild(tr);
  15863. });
  15864. }
  15865. function openAddUserModal() {
  15866. document.getElementById('user-add-username').value = '';
  15867. document.getElementById('user-add-password').value = '';
  15868. document.getElementById('user-add-confirm').value = '';
  15869. document.getElementById('user-add-role').value = 'full';
  15870. document.getElementById('user-add-comment').value = '';
  15871. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15872. document.getElementById('user-add-username')?.focus();
  15873. }
  15874. function closeAddUserModal() {
  15875. document.getElementById('modal-add-user')?.classList.add('hidden');
  15876. }
  15877. async function submitAddUser(event) {
  15878. event.preventDefault();
  15879. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15880. const password = document.getElementById('user-add-password')?.value || '';
  15881. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15882. const role = document.getElementById('user-add-role')?.value || 'full';
  15883. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15884. if (password !== confirm) {
  15885. showToast('Validation Error', 'Passwords do not match', 'warning');
  15886. return;
  15887. }
  15888. if (password.length < 4) {
  15889. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15890. return;
  15891. }
  15892. try {
  15893. const res = await fetch(`${API_BASE}/users`, {
  15894. method: 'POST',
  15895. headers: { 'Content-Type': 'application/json' },
  15896. body: JSON.stringify({ username, password, role, comment })
  15897. });
  15898. const data = await res.json();
  15899. if (res.ok) {
  15900. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15901. closeAddUserModal();
  15902. loadUsers(false);
  15903. } else {
  15904. showToast('Error', data.message || 'Failed to create user', 'error');
  15905. }
  15906. } catch (err) {
  15907. showToast('Error', err.message, 'error');
  15908. }
  15909. }
  15910. function openEditUserModal(username) {
  15911. const user = (state.users || []).find(u => u.username === username);
  15912. if (!user) return;
  15913. document.getElementById('user-edit-username').value = user.username;
  15914. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15915. document.getElementById('user-edit-role').value = user.role || 'read';
  15916. document.getElementById('user-edit-comment').value = user.comment || '';
  15917. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15918. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15919. }
  15920. function closeEditUserModal() {
  15921. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15922. }
  15923. async function submitEditUser(event) {
  15924. event.preventDefault();
  15925. const username = document.getElementById('user-edit-username')?.value;
  15926. const role = document.getElementById('user-edit-role')?.value || 'read';
  15927. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15928. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15929. try {
  15930. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15931. method: 'PUT',
  15932. headers: { 'Content-Type': 'application/json' },
  15933. body: JSON.stringify({ role, comment, disabled })
  15934. });
  15935. const data = await res.json();
  15936. if (res.ok) {
  15937. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15938. closeEditUserModal();
  15939. loadUsers(false);
  15940. // If updated own role/disabled status, refresh self profile
  15941. if (username === state.currentUser?.username) {
  15942. checkAuthStatus();
  15943. }
  15944. } else {
  15945. showToast('Error', data.message || 'Failed to update user', 'error');
  15946. }
  15947. } catch (err) {
  15948. showToast('Error', err.message, 'error');
  15949. }
  15950. }
  15951. function openAdminResetPasswordModal(username) {
  15952. document.getElementById('admin-reset-username').value = username;
  15953. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15954. document.getElementById('admin-reset-new-pw').value = '';
  15955. document.getElementById('admin-reset-confirm-pw').value = '';
  15956. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15957. document.getElementById('admin-reset-new-pw')?.focus();
  15958. }
  15959. function closeAdminResetPasswordModal() {
  15960. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15961. }
  15962. async function submitAdminResetPassword(event) {
  15963. event.preventDefault();
  15964. const username = document.getElementById('admin-reset-username')?.value;
  15965. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15966. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15967. if (newPassword !== confirm) {
  15968. showToast('Validation Error', 'Passwords do not match', 'warning');
  15969. return;
  15970. }
  15971. if (newPassword.length < 4) {
  15972. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15973. return;
  15974. }
  15975. try {
  15976. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15977. method: 'POST',
  15978. headers: { 'Content-Type': 'application/json' },
  15979. body: JSON.stringify({ new_password: newPassword })
  15980. });
  15981. const data = await res.json();
  15982. if (res.ok) {
  15983. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15984. closeAdminResetPasswordModal();
  15985. } else {
  15986. showToast('Error', data.message || 'Failed to reset password', 'error');
  15987. }
  15988. } catch (err) {
  15989. showToast('Error', err.message, 'error');
  15990. }
  15991. }
  15992. async function deleteUser(username) {
  15993. if (username === state.currentUser?.username) {
  15994. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15995. return;
  15996. }
  15997. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15998. return;
  15999. }
  16000. try {
  16001. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16002. method: 'DELETE'
  16003. });
  16004. const data = await res.json();
  16005. if (res.ok) {
  16006. showToast('User Deleted', `User ${username} has been removed`, 'success');
  16007. loadUsers(false);
  16008. } else {
  16009. showToast('Error', data.message || 'Failed to delete user', 'error');
  16010. }
  16011. } catch (err) {
  16012. showToast('Error', err.message, 'error');
  16013. }
  16014. }
  16015. function openSelfPasswordModal() {
  16016. document.getElementById('self-current-password').value = '';
  16017. document.getElementById('self-new-password').value = '';
  16018. document.getElementById('self-confirm-password').value = '';
  16019. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16020. document.getElementById('self-current-password')?.focus();
  16021. }
  16022. function closeSelfPasswordModal() {
  16023. document.getElementById('modal-self-password')?.classList.add('hidden');
  16024. }
  16025. async function submitSelfPassword(event) {
  16026. event.preventDefault();
  16027. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16028. const newPassword = document.getElementById('self-new-password')?.value || '';
  16029. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16030. if (newPassword !== confirm) {
  16031. showToast('Validation Error', 'New passwords do not match', 'warning');
  16032. return;
  16033. }
  16034. if (newPassword.length < 4) {
  16035. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16036. return;
  16037. }
  16038. try {
  16039. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16040. method: 'POST',
  16041. headers: { 'Content-Type': 'application/json' },
  16042. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16043. });
  16044. const data = await res.json();
  16045. if (res.ok) {
  16046. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16047. closeSelfPasswordModal();
  16048. } else {
  16049. showToast('Error', data.message || 'Failed to change password', 'error');
  16050. }
  16051. } catch (err) {
  16052. showToast('Error', err.message, 'error');
  16053. }
  16054. }
  16055. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16056. state.services = [];
  16057. async function loadServices(manual = false) {
  16058. try {
  16059. const res = await fetch(`${API_BASE}/system/services`);
  16060. if (!res.ok) throw new Error('Failed to load services');
  16061. const data = await res.json();
  16062. state.services = data || [];
  16063. renderServicesTable();
  16064. updateCertificatesBadges();
  16065. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16066. } catch (err) {
  16067. if (manual) showToast('Error', err.message, 'error');
  16068. }
  16069. }
  16070. function renderServicesTable() {
  16071. const tbody = document.getElementById('services-table-body');
  16072. if (!tbody) return;
  16073. if (!state.services || state.services.length === 0) {
  16074. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16075. return;
  16076. }
  16077. tbody.innerHTML = state.services.map(s => {
  16078. const isOff = s.disabled;
  16079. const statusBadge = isOff
  16080. ? '<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>'
  16081. : '<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>';
  16082. const toggleBtn = isOff
  16083. ? `<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>`
  16084. : `<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>`;
  16085. let certBadge = '';
  16086. if (s.name === 'www-ssl') {
  16087. if (s.certificate) {
  16088. 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>`;
  16089. } else {
  16090. 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>`;
  16091. }
  16092. }
  16093. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16094. return `
  16095. <tr class="hover:bg-slate-800/40 transition">
  16096. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16097. <td class="py-3 px-4">
  16098. <div class="flex items-center gap-2">
  16099. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16100. <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">
  16101. <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>
  16102. </button>
  16103. </div>
  16104. </td>
  16105. <td class="py-3 px-4">${statusBadge}</td>
  16106. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16107. <td class="py-3 px-4 text-right">
  16108. <div class="flex items-center justify-end gap-2">
  16109. <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">
  16110. <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>
  16111. <span>Edit</span>
  16112. </button>
  16113. ${toggleBtn}
  16114. </div>
  16115. </td>
  16116. </tr>
  16117. `;
  16118. }).join('');
  16119. }
  16120. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16121. document.getElementById('modal-service-name').value = serviceName;
  16122. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16123. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16124. document.getElementById('modal-service-port').value = currentPort;
  16125. const hintEl = document.getElementById('modal-service-port-hint');
  16126. const warnEl = document.getElementById('modal-service-warning');
  16127. const certGroup = document.getElementById('modal-service-cert-group');
  16128. const certSelect = document.getElementById('modal-service-cert-select');
  16129. if (serviceName === 'www') {
  16130. hintEl.textContent = 'Default HTTP web port: 80';
  16131. warnEl.classList.remove('hidden');
  16132. certGroup.classList.add('hidden');
  16133. } else if (serviceName === 'www-ssl') {
  16134. hintEl.textContent = 'Default HTTPS web port: 443';
  16135. warnEl.classList.remove('hidden');
  16136. certGroup.classList.remove('hidden');
  16137. const populateCertOptions = (certs) => {
  16138. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16139. (certs || []).forEach(c => {
  16140. const opt = document.createElement('option');
  16141. opt.value = c.name;
  16142. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16143. if (c.name === currentCert) opt.selected = true;
  16144. certSelect.appendChild(opt);
  16145. });
  16146. };
  16147. if (state.certificates && state.certificates.length > 0) {
  16148. populateCertOptions(state.certificates);
  16149. } else {
  16150. loadCertificates(false).then(() => {
  16151. populateCertOptions(state.certificates);
  16152. });
  16153. }
  16154. } else if (serviceName === 'telnet') {
  16155. hintEl.textContent = 'Default Telnet console port: 8282';
  16156. warnEl.classList.add('hidden');
  16157. certGroup.classList.add('hidden');
  16158. } else if (serviceName === 'ssh') {
  16159. hintEl.textContent = 'Default SSH port: 2222';
  16160. warnEl.classList.add('hidden');
  16161. certGroup.classList.add('hidden');
  16162. } else {
  16163. hintEl.textContent = '';
  16164. warnEl.classList.add('hidden');
  16165. certGroup.classList.add('hidden');
  16166. }
  16167. const modal = document.getElementById('modal-service-edit');
  16168. modal.classList.remove('hidden');
  16169. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16170. }
  16171. function closeEditServiceModal() {
  16172. const modal = document.getElementById('modal-service-edit');
  16173. if (modal) modal.classList.add('hidden');
  16174. }
  16175. async function submitSaveServicePort(event) {
  16176. event.preventDefault();
  16177. const name = document.getElementById('modal-service-name').value;
  16178. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16179. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16180. if (isNaN(port) || port < 1 || port > 65535) {
  16181. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16182. return;
  16183. }
  16184. const certSelect = document.getElementById('modal-service-cert-select');
  16185. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16186. try {
  16187. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16188. method: 'POST',
  16189. headers: { 'Content-Type': 'application/json' },
  16190. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16191. });
  16192. if (!res.ok) {
  16193. const errData = await res.json();
  16194. throw new Error(errData.message || 'Failed to update service settings');
  16195. }
  16196. closeEditServiceModal();
  16197. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16198. await loadServices();
  16199. } catch (err) {
  16200. showToast('Error', err.message, 'error');
  16201. }
  16202. }
  16203. async function toggleServiceState(serviceName, newDisabled) {
  16204. if (serviceName === 'www' && newDisabled) {
  16205. 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?")) {
  16206. return;
  16207. }
  16208. }
  16209. if (serviceName === 'www-ssl' && !newDisabled) {
  16210. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16211. if (!sslSvc || !sslSvc.certificate) {
  16212. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16213. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16214. return;
  16215. }
  16216. }
  16217. try {
  16218. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16219. method: 'POST',
  16220. headers: { 'Content-Type': 'application/json' },
  16221. body: JSON.stringify({ disabled: newDisabled })
  16222. });
  16223. if (!res.ok) {
  16224. const errData = await res.json();
  16225. throw new Error(errData.message || 'Failed to update service');
  16226. }
  16227. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16228. await loadServices();
  16229. } catch (err) {
  16230. showToast('Error', err.message, 'error');
  16231. }
  16232. }
  16233. // ==================== SYSTEM LOGS (/log) ====================
  16234. state.logs = [];
  16235. let logsTimer = null;
  16236. async function loadLogs(manual = false) {
  16237. const limitEl = document.getElementById('logs-limit-select');
  16238. const limit = limitEl ? limitEl.value : '100';
  16239. try {
  16240. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16241. if (!res.ok) throw new Error('Failed to load logs');
  16242. const data = await res.json();
  16243. state.logs = data.logs || [];
  16244. renderLogsTable();
  16245. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16246. } catch (err) {
  16247. if (manual) showToast('Error', err.message, 'error');
  16248. }
  16249. // Setup auto-refresh if enabled and on logs tab
  16250. if (!logsTimer && state.currentUser) {
  16251. logsTimer = setInterval(() => {
  16252. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16253. const auto = document.getElementById('logs-auto-refresh');
  16254. if (auto && auto.checked) {
  16255. loadLogs(false);
  16256. }
  16257. }
  16258. }, 3000);
  16259. }
  16260. }
  16261. function renderLogsTable() {
  16262. const tbody = document.getElementById('logs-table-body');
  16263. if (!tbody) return;
  16264. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16265. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16266. const filtered = state.logs.filter(entry => {
  16267. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16268. return false;
  16269. }
  16270. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16271. return false;
  16272. }
  16273. return true;
  16274. });
  16275. if (filtered.length === 0) {
  16276. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16277. return;
  16278. }
  16279. tbody.innerHTML = filtered.map(l => {
  16280. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16281. const topLower = l.topics.toLowerCase();
  16282. if (topLower.includes('auth')) {
  16283. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16284. } else if (topLower.includes('dhcp')) {
  16285. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16286. } else if (topLower.includes('route')) {
  16287. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16288. } else if (topLower.includes('firewall')) {
  16289. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16290. } else if (topLower.includes('error')) {
  16291. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16292. } else if (topLower.includes('system')) {
  16293. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16294. }
  16295. const d = new Date(l.time);
  16296. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16297. return `
  16298. <tr class="hover:bg-slate-800/40 transition">
  16299. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16300. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16301. <td class="py-2 px-3 whitespace-nowrap">
  16302. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16303. </td>
  16304. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16305. </tr>
  16306. `;
  16307. }).join('');
  16308. }
  16309. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16310. state.certificates = [];
  16311. async function loadCertificates(manual = false) {
  16312. try {
  16313. const res = await fetch(`${API_BASE}/certificates`);
  16314. if (!res.ok) throw new Error('Failed to load certificates');
  16315. state.certificates = await res.json() || [];
  16316. updateCertificatesBadges();
  16317. renderCertificatesTable();
  16318. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16319. } catch (err) {
  16320. if (manual) showToast('Error', err.message, 'error');
  16321. }
  16322. }
  16323. function updateCertificatesBadges() {
  16324. const total = (state.certificates || []).length;
  16325. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16326. const bCount = document.getElementById('badge-certs-count');
  16327. if (bCount) bCount.innerText = total;
  16328. const kpiTotal = document.getElementById('kpi-certs-total');
  16329. if (kpiTotal) kpiTotal.innerText = total;
  16330. const kpiCA = document.getElementById('kpi-certs-ca');
  16331. if (kpiCA) kpiCA.innerText = caCount;
  16332. const kpiHttps = document.getElementById('kpi-https-status');
  16333. if (kpiHttps) {
  16334. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16335. if (sslSvc) {
  16336. if (!sslSvc.disabled) {
  16337. 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>`;
  16338. } else {
  16339. 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>`;
  16340. }
  16341. }
  16342. }
  16343. }
  16344. function renderCertificatesTable() {
  16345. const tbody = document.getElementById('certs-table-body');
  16346. if (!tbody) return;
  16347. if (!state.certificates || state.certificates.length === 0) {
  16348. 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>';
  16349. return;
  16350. }
  16351. tbody.innerHTML = state.certificates.map(c => {
  16352. let typeBadge = '';
  16353. if (c.is_ca) {
  16354. 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>';
  16355. } else if (c.type === 'acme') {
  16356. 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>';
  16357. } else if (c.issuer && c.issuer !== c.common_name) {
  16358. 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>';
  16359. } else {
  16360. 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>';
  16361. }
  16362. const sansHtml = (c.sans && c.sans.length > 0)
  16363. ? 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('')
  16364. : '<span class="text-slate-500">-</span>';
  16365. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16366. let validStr = '-';
  16367. let validBadge = '';
  16368. if (validTo && !isNaN(validTo.getTime())) {
  16369. const now = new Date();
  16370. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16371. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16372. if (daysLeft < 0) {
  16373. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16374. } else if (daysLeft < 30) {
  16375. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16376. } else {
  16377. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16378. }
  16379. }
  16380. return `
  16381. <tr class="hover:bg-slate-800/40 transition">
  16382. <td class="py-3 px-4">${typeBadge}</td>
  16383. <td class="py-3 px-4">
  16384. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16385. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16386. </td>
  16387. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16388. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16389. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16390. <span>${validStr}</span> ${validBadge}
  16391. ${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>` : ''}
  16392. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16393. </td>
  16394. <td class="py-3 px-4 text-right whitespace-nowrap">
  16395. <div class="flex items-center justify-end gap-1.5">
  16396. <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">
  16397. <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>
  16398. <span>View</span>
  16399. </button>
  16400. <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">
  16401. <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>
  16402. </button>
  16403. </div>
  16404. </td>
  16405. </tr>
  16406. `;
  16407. }).join('');
  16408. }
  16409. // Create CA
  16410. function openCreateCAModal() {
  16411. document.getElementById('form-create-ca').reset();
  16412. document.getElementById('ca-days').value = '3650';
  16413. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16414. document.getElementById('ca-country').value = 'GR';
  16415. document.getElementById('ca-key-type').value = 'RSA-2048';
  16416. document.getElementById('modal-create-ca').classList.remove('hidden');
  16417. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16418. }
  16419. function closeCreateCAModal() {
  16420. document.getElementById('modal-create-ca').classList.add('hidden');
  16421. }
  16422. async function submitCreateCA(event) {
  16423. event.preventDefault();
  16424. const payload = {
  16425. name: document.getElementById('ca-name').value.trim(),
  16426. common_name: document.getElementById('ca-cn').value.trim(),
  16427. organization: document.getElementById('ca-org').value.trim(),
  16428. country: document.getElementById('ca-country').value.trim(),
  16429. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16430. key_type: document.getElementById('ca-key-type').value
  16431. };
  16432. try {
  16433. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16434. method: 'POST',
  16435. headers: { 'Content-Type': 'application/json' },
  16436. body: JSON.stringify(payload)
  16437. });
  16438. if (!res.ok) {
  16439. const errData = await res.json();
  16440. throw new Error(errData.message || 'Failed to create CA');
  16441. }
  16442. closeCreateCAModal();
  16443. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16444. await loadCertificates();
  16445. } catch (err) {
  16446. showToast('Error', err.message, 'error');
  16447. }
  16448. }
  16449. // Create Cert
  16450. function openCreateCertModal() {
  16451. document.getElementById('form-create-cert').reset();
  16452. document.getElementById('cert-days').value = '730';
  16453. document.getElementById('cert-key-type').value = 'RSA-2048';
  16454. const caSelect = document.getElementById('cert-ca-select');
  16455. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16456. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16457. const opt = document.createElement('option');
  16458. opt.value = ca.name;
  16459. opt.textContent = `${ca.name} (${ca.common_name})`;
  16460. caSelect.appendChild(opt);
  16461. });
  16462. document.getElementById('modal-create-cert').classList.remove('hidden');
  16463. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16464. }
  16465. function closeCreateCertModal() {
  16466. document.getElementById('modal-create-cert').classList.add('hidden');
  16467. }
  16468. async function submitCreateCert(event) {
  16469. event.preventDefault();
  16470. const rawSans = document.getElementById('cert-sans').value;
  16471. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16472. const caName = document.getElementById('cert-ca-select').value;
  16473. const payload = {
  16474. name: document.getElementById('cert-name').value.trim(),
  16475. common_name: document.getElementById('cert-cn').value.trim(),
  16476. ca_name: caName,
  16477. sans: sansList,
  16478. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16479. key_type: document.getElementById('cert-key-type').value,
  16480. is_server: true
  16481. };
  16482. try {
  16483. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16484. method: 'POST',
  16485. headers: { 'Content-Type': 'application/json' },
  16486. body: JSON.stringify(payload)
  16487. });
  16488. if (!res.ok) {
  16489. const errData = await res.json();
  16490. throw new Error(errData.message || 'Failed to issue certificate');
  16491. }
  16492. closeCreateCertModal();
  16493. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16494. await loadCertificates();
  16495. } catch (err) {
  16496. showToast('Error', err.message, 'error');
  16497. }
  16498. }
  16499. // Let's Encrypt
  16500. function openLetsEncryptModal() {
  16501. document.getElementById('form-letsencrypt').reset();
  16502. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16503. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16504. }
  16505. function closeLetsEncryptModal() {
  16506. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16507. }
  16508. async function submitLetsEncrypt(event) {
  16509. event.preventDefault();
  16510. const domain = document.getElementById('le-domain').value.trim();
  16511. const email = document.getElementById('le-email').value.trim();
  16512. let name = document.getElementById('le-name').value.trim();
  16513. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16514. const staging = document.getElementById('le-staging').checked;
  16515. const btn = document.getElementById('btn-submit-letsencrypt');
  16516. const origBtnHtml = btn.innerHTML;
  16517. btn.disabled = true;
  16518. 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>`;
  16519. try {
  16520. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16521. method: 'POST',
  16522. headers: { 'Content-Type': 'application/json' },
  16523. body: JSON.stringify({
  16524. name: name,
  16525. domain: domain,
  16526. email: email,
  16527. staging: staging
  16528. })
  16529. });
  16530. if (!res.ok) {
  16531. const errData = await res.json();
  16532. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16533. }
  16534. closeLetsEncryptModal();
  16535. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16536. await loadCertificates();
  16537. } catch (err) {
  16538. showToast('Let\'s Encrypt Error', err.message, 'error');
  16539. } finally {
  16540. btn.disabled = false;
  16541. btn.innerHTML = origBtnHtml;
  16542. }
  16543. }
  16544. // Import Cert
  16545. function openImportCertModal() {
  16546. document.getElementById('form-import-cert').reset();
  16547. document.getElementById('modal-import-cert').classList.remove('hidden');
  16548. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16549. }
  16550. function closeImportCertModal() {
  16551. document.getElementById('modal-import-cert').classList.add('hidden');
  16552. }
  16553. async function submitImportCert(event) {
  16554. event.preventDefault();
  16555. const payload = {
  16556. name: document.getElementById('import-cert-name').value.trim(),
  16557. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16558. key_pem: document.getElementById('import-key-pem').value.trim()
  16559. };
  16560. try {
  16561. const res = await fetch(`${API_BASE}/certificates/import`, {
  16562. method: 'POST',
  16563. headers: { 'Content-Type': 'application/json' },
  16564. body: JSON.stringify(payload)
  16565. });
  16566. if (!res.ok) {
  16567. const errData = await res.json();
  16568. throw new Error(errData.message || 'Failed to import certificate');
  16569. }
  16570. closeImportCertModal();
  16571. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16572. await loadCertificates();
  16573. } catch (err) {
  16574. showToast('Error', err.message, 'error');
  16575. }
  16576. }
  16577. // View / Export Modal
  16578. async function openViewCertModal(name) {
  16579. const c = (state.certificates || []).find(x => x.name === name);
  16580. if (!c) return;
  16581. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16582. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16583. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16584. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16585. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16586. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16587. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16588. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16589. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16590. document.getElementById('modal-view-cert').classList.remove('hidden');
  16591. try {
  16592. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16593. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16594. const data = await res.json();
  16595. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16596. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16597. } catch (err) {
  16598. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16599. document.getElementById('view-key-pem-text').value = '';
  16600. }
  16601. }
  16602. function closeViewCertModal() {
  16603. document.getElementById('modal-view-cert').classList.add('hidden');
  16604. }
  16605. function copyCertPEM() {
  16606. const text = document.getElementById('view-cert-pem-text').value;
  16607. if (!text) return;
  16608. navigator.clipboard.writeText(text).then(() => {
  16609. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16610. }).catch(() => {
  16611. showToast('Error', 'Failed to copy to clipboard', 'error');
  16612. });
  16613. }
  16614. function copyKeyPEM() {
  16615. const text = document.getElementById('view-key-pem-text').value;
  16616. if (!text) return;
  16617. navigator.clipboard.writeText(text).then(() => {
  16618. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16619. }).catch(() => {
  16620. showToast('Error', 'Failed to copy to clipboard', 'error');
  16621. });
  16622. }
  16623. async function deleteCertificate(name) {
  16624. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16625. return;
  16626. }
  16627. try {
  16628. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16629. method: 'DELETE'
  16630. });
  16631. if (!res.ok) {
  16632. const errData = await res.json();
  16633. throw new Error(errData.message || 'Failed to delete certificate');
  16634. }
  16635. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16636. await loadCertificates();
  16637. } catch (err) {
  16638. showToast('Error', err.message, 'error');
  16639. }
  16640. }
  16641. // Refresh immediately when returning to a backgrounded controller tab.
  16642. document.addEventListener('visibilitychange', () => {
  16643. if (!state.currentUser) return;
  16644. if (document.hidden) {
  16645. if (trafficEventSource) trafficEventSource.close();
  16646. trafficEventSource = null;
  16647. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16648. trafficPollFallback = null;
  16649. } else {
  16650. fetchData(false);
  16651. initLiveTrafficStream();
  16652. if (state.activeTab === 'bwtest') loadBwTestView();
  16653. }
  16654. });
  16655. async function loadUpdateStatus(populate = true) {
  16656. try {
  16657. const res = await fetch(`${API_BASE}/update/status`);
  16658. if (!res.ok) throw new Error(await responseError(res));
  16659. const data = await res.json();
  16660. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16661. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16662. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16663. document.getElementById('update-state').textContent = data.state || 'idle';
  16664. document.getElementById('update-log').textContent = data.log || '';
  16665. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16666. }
  16667. async function saveUpdateConfig() {
  16668. try {
  16669. const repository = document.getElementById('update-repository').value.trim();
  16670. const branch = 'master';
  16671. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16672. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16673. if (!res.ok) throw new Error(await responseError(res));
  16674. document.getElementById('update-install-button').disabled = true;
  16675. document.getElementById('update-available').textContent = '—';
  16676. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16677. await loadUpdateStatus(false);
  16678. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16679. }
  16680. async function checkUpdate() {
  16681. try {
  16682. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16683. if (!res.ok) throw new Error(await responseError(res));
  16684. const data = await res.json();
  16685. document.getElementById('update-available').textContent = data.available_version;
  16686. document.getElementById('update-install-button').disabled = !data.update_available;
  16687. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16688. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16689. }
  16690. async function startUpdate(action) {
  16691. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16692. try {
  16693. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16694. if (!res.ok) throw new Error(await responseError(res));
  16695. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16696. await loadUpdateStatus(false);
  16697. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16698. }
  16699. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16700. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16701. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16702. function safeFirewallRow(row) {
  16703. const result = {...row};
  16704. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16705. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16706. return result;
  16707. }
  16708. function setFirewallDays(prefix, days) {
  16709. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16710. 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); }
  16711. }
  16712. function getFirewallDays(prefix) {
  16713. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16714. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16715. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16716. return selected.join(',');
  16717. }
  16718. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16719. const id = document.getElementById(kind+'-modal-id')?.value;
  16720. if (!id) { resetDisplay(); return; }
  16721. try {
  16722. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16723. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16724. resetDisplay(); await loadFirewall(false);
  16725. } catch(error) { showToast('Error', error.message, 'error'); }
  16726. }
  16727. function reviewLegacyFirewallSettings(kind, id) {
  16728. if (!id) return true;
  16729. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16730. const rule = (rows || []).find(r => r.id === id);
  16731. if (!rule) return true;
  16732. 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'];
  16733. const present = unsupported.filter(key => rule[key]);
  16734. if (!present.length) return true;
  16735. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16736. }
  16737. function refreshFirewallRejectTypes() {
  16738. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16739. const old=select.value;
  16740. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16741. 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'];
  16742. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16743. if(types.includes(old))select.value=old;
  16744. }
  16745. function setFirewallActionSelection(kind, value) {
  16746. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16747. if(!Array.from(select.options).some(option=>option.value===value)) {
  16748. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16749. }
  16750. select.value=value;
  16751. }
  16752. // ==========================================
  16753. // REVERSE PROXY & APPLICATION GATEWAY
  16754. // ==========================================
  16755. state.proxyRules = [];
  16756. state.proxyConfig = null;
  16757. async function loadReverseProxy(manual = false) {
  16758. try {
  16759. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16760. fetch(`${API_BASE}/proxy/config`),
  16761. fetch(`${API_BASE}/proxy/rules`),
  16762. fetch(`${API_BASE}/certificates`).catch(() => null)
  16763. ]);
  16764. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16765. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16766. state.proxyConfig = await cfgRes.json();
  16767. state.proxyRules = await rulesRes.json() || [];
  16768. if (certsRes && certsRes.ok) {
  16769. state.certificates = await certsRes.json() || [];
  16770. }
  16771. renderProxyRules(state.proxyRules);
  16772. updateProxyMetrics();
  16773. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16774. } catch (err) {
  16775. console.error('loadReverseProxy error:', err);
  16776. if (manual) showToast('Error', err.message, 'error');
  16777. }
  16778. }
  16779. function updateProxyMetrics() {
  16780. const badge = document.getElementById('badge-proxy-count');
  16781. if (badge) badge.textContent = (state.proxyRules || []).length;
  16782. const metricRules = document.getElementById('proxy-metric-rules');
  16783. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16784. const cfg = state.proxyConfig;
  16785. const statusEl = document.getElementById('proxy-metric-status');
  16786. const portsEl = document.getElementById('proxy-metric-ports');
  16787. if (cfg) {
  16788. if (statusEl) {
  16789. if (cfg.enabled) {
  16790. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16791. } else {
  16792. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16793. }
  16794. }
  16795. if (portsEl) {
  16796. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16797. }
  16798. }
  16799. let totalRequests = 0;
  16800. const certSet = new Set();
  16801. (state.proxyRules || []).forEach(r => {
  16802. totalRequests += (r.stats && r.stats.requests) || 0;
  16803. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16804. });
  16805. const metricRequests = document.getElementById('proxy-metric-requests');
  16806. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16807. const metricCerts = document.getElementById('proxy-metric-certs');
  16808. if (metricCerts) metricCerts.textContent = certSet.size;
  16809. }
  16810. function renderProxyRules(rules) {
  16811. const tbody = document.getElementById('proxy-rules-table-body');
  16812. if (!tbody) return;
  16813. if (!rules || rules.length === 0) {
  16814. 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>';
  16815. return;
  16816. }
  16817. tbody.innerHTML = rules.map(r => {
  16818. const isEnabled = r.enabled !== false;
  16819. 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>';
  16820. 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>`;
  16821. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16822. 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>';
  16823. 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>';
  16824. 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>` : '';
  16825. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16826. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16827. return `
  16828. <tr class="hover:bg-slate-800/40 transition">
  16829. <td class="py-3 px-4">
  16830. <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'}">
  16831. <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>
  16832. </button>
  16833. </td>
  16834. <td class="py-3 px-4">
  16835. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16836. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16837. </td>
  16838. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16839. ${domainsStr}
  16840. </td>
  16841. <td class="py-3 px-4">
  16842. ${pathBadge}
  16843. </td>
  16844. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16845. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16846. </td>
  16847. <td class="py-3 px-4 whitespace-nowrap">
  16848. ${protoBadge}${certBadge}
  16849. </td>
  16850. <td class="py-3 px-4 font-mono">
  16851. ${stripBadge}
  16852. </td>
  16853. <td class="py-3 px-4 font-mono text-slate-300">
  16854. ${requests}
  16855. </td>
  16856. <td class="py-3 px-4 text-right whitespace-nowrap">
  16857. <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>
  16858. <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>
  16859. </td>
  16860. </tr>
  16861. `;
  16862. }).join('');
  16863. }
  16864. function populateProxyCertDropdown(selectedVal = '') {
  16865. const select = document.getElementById('proxy-rule-cert');
  16866. if (!select) return;
  16867. const certs = state.certificates || [];
  16868. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16869. certs.filter(c => !c.is_ca).forEach(c => {
  16870. const opt = document.createElement('option');
  16871. opt.value = c.name;
  16872. const cn = c.common_name ? ` (${c.common_name})` : '';
  16873. opt.textContent = `${c.name}${cn}`;
  16874. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16875. opt.selected = true;
  16876. }
  16877. select.appendChild(opt);
  16878. });
  16879. }
  16880. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16881. const select = document.getElementById('proxy-cfg-default-cert');
  16882. if (!select) return;
  16883. const certs = state.certificates || [];
  16884. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16885. certs.filter(c => !c.is_ca).forEach(c => {
  16886. const opt = document.createElement('option');
  16887. opt.value = c.name;
  16888. const cn = c.common_name ? ` (${c.common_name})` : '';
  16889. opt.textContent = `${c.name}${cn}`;
  16890. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16891. opt.selected = true;
  16892. }
  16893. select.appendChild(opt);
  16894. });
  16895. }
  16896. function onProxyProtoChange() {
  16897. const proto = document.getElementById('proxy-rule-proto')?.value;
  16898. const certSelect = document.getElementById('proxy-rule-cert');
  16899. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16900. if (proto === 'http') {
  16901. if (certSelect) certSelect.disabled = true;
  16902. if (redirectCheck) redirectCheck.disabled = true;
  16903. } else {
  16904. if (certSelect) certSelect.disabled = false;
  16905. if (redirectCheck) redirectCheck.disabled = false;
  16906. }
  16907. }
  16908. function openAddProxyRuleModal() {
  16909. const modal = document.getElementById('modal-proxy-rule');
  16910. if (!modal) return;
  16911. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16912. <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>
  16913. <span>Add Reverse Proxy Rule</span>
  16914. `;
  16915. document.getElementById('proxy-rule-id').value = '';
  16916. document.getElementById('proxy-rule-name').value = '';
  16917. document.getElementById('proxy-rule-domains').value = '';
  16918. document.getElementById('proxy-rule-path').value = '/';
  16919. document.getElementById('proxy-rule-target').value = '';
  16920. document.getElementById('proxy-rule-proto').value = 'both';
  16921. document.getElementById('proxy-rule-strip-path').checked = false;
  16922. document.getElementById('proxy-rule-http-to-https').checked = false;
  16923. document.getElementById('proxy-rule-preserve-host').checked = false;
  16924. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16925. document.getElementById('proxy-rule-enabled').checked = true;
  16926. document.getElementById('proxy-rule-comment').value = '';
  16927. populateProxyCertDropdown('');
  16928. onProxyProtoChange();
  16929. modal.classList.remove('hidden');
  16930. }
  16931. function openEditProxyRuleModal(id) {
  16932. const modal = document.getElementById('modal-proxy-rule');
  16933. if (!modal) return;
  16934. const rule = (state.proxyRules || []).find(r => r.id === id);
  16935. if (!rule) {
  16936. showToast('Error', 'Rule not found', 'error');
  16937. return;
  16938. }
  16939. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16940. <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>
  16941. <span>Edit Reverse Proxy Rule</span>
  16942. `;
  16943. document.getElementById('proxy-rule-id').value = rule.id || '';
  16944. document.getElementById('proxy-rule-name').value = rule.name || '';
  16945. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16946. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16947. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16948. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16949. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16950. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16951. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16952. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16953. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16954. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16955. populateProxyCertDropdown(rule.certificate || '');
  16956. onProxyProtoChange();
  16957. modal.classList.remove('hidden');
  16958. }
  16959. function closeProxyRuleModal() {
  16960. const modal = document.getElementById('modal-proxy-rule');
  16961. if (modal) modal.classList.add('hidden');
  16962. }
  16963. async function saveProxyRule(event) {
  16964. event.preventDefault();
  16965. const id = document.getElementById('proxy-rule-id').value;
  16966. const name = document.getElementById('proxy-rule-name').value.trim();
  16967. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16968. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16969. const target = document.getElementById('proxy-rule-target').value.trim();
  16970. const proto = document.getElementById('proxy-rule-proto').value;
  16971. const cert = document.getElementById('proxy-rule-cert').value;
  16972. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16973. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16974. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16975. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16976. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16977. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16978. let domains = [];
  16979. if (rawDomains && rawDomains !== '*') {
  16980. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16981. }
  16982. const payload = {
  16983. id: id || undefined,
  16984. name,
  16985. domains,
  16986. path: pathVal,
  16987. target_url: target,
  16988. protocol: proto,
  16989. certificate: cert,
  16990. strip_path: stripPath,
  16991. http_to_https: httpToHttps,
  16992. preserve_host: preserveHost,
  16993. insecure_tls: insecureTLS,
  16994. enabled,
  16995. comment
  16996. };
  16997. try {
  16998. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16999. const method = id ? 'PUT' : 'POST';
  17000. const res = await fetch(url, {
  17001. method,
  17002. headers: { 'Content-Type': 'application/json' },
  17003. body: JSON.stringify(payload)
  17004. });
  17005. if (!res.ok) {
  17006. const errData = await res.json().catch(() => ({}));
  17007. throw new Error(errData.message || 'Failed to save proxy rule');
  17008. }
  17009. closeProxyRuleModal();
  17010. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  17011. await loadReverseProxy(false);
  17012. } catch (err) {
  17013. showToast('Error', err.message, 'error');
  17014. }
  17015. }
  17016. async function deleteProxyRule(id) {
  17017. const rule = (state.proxyRules || []).find(r => r.id === id);
  17018. const name = rule ? rule.name : id;
  17019. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17020. return;
  17021. }
  17022. try {
  17023. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17024. method: 'DELETE'
  17025. });
  17026. if (!res.ok) {
  17027. const errData = await res.json().catch(() => ({}));
  17028. throw new Error(errData.message || 'Failed to delete rule');
  17029. }
  17030. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17031. await loadReverseProxy(false);
  17032. } catch (err) {
  17033. showToast('Error', err.message, 'error');
  17034. }
  17035. }
  17036. async function toggleProxyRuleState(id, currentState) {
  17037. try {
  17038. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17039. method: 'POST',
  17040. headers: { 'Content-Type': 'application/json' },
  17041. body: JSON.stringify({ enabled: !currentState })
  17042. });
  17043. if (!res.ok) {
  17044. const errData = await res.json().catch(() => ({}));
  17045. throw new Error(errData.message || 'Failed to toggle rule state');
  17046. }
  17047. await loadReverseProxy(false);
  17048. } catch (err) {
  17049. showToast('Error', err.message, 'error');
  17050. }
  17051. }
  17052. function openProxyConfigModal() {
  17053. const modal = document.getElementById('modal-proxy-config');
  17054. if (!modal) return;
  17055. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17056. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17057. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17058. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17059. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17060. modal.classList.remove('hidden');
  17061. }
  17062. function closeProxyConfigModal() {
  17063. const modal = document.getElementById('modal-proxy-config');
  17064. if (modal) modal.classList.add('hidden');
  17065. }
  17066. async function saveProxyConfig(event) {
  17067. event.preventDefault();
  17068. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17069. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17070. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17071. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17072. const payload = {
  17073. enabled,
  17074. http_port: httpPort,
  17075. https_port: httpsPort,
  17076. default_cert: defaultCert
  17077. };
  17078. try {
  17079. const res = await fetch(`${API_BASE}/proxy/config`, {
  17080. method: 'POST',
  17081. headers: { 'Content-Type': 'application/json' },
  17082. body: JSON.stringify(payload)
  17083. });
  17084. if (!res.ok) {
  17085. const errData = await res.json().catch(() => ({}));
  17086. throw new Error(errData.message || 'Failed to update proxy settings');
  17087. }
  17088. closeProxyConfigModal();
  17089. showToast('Success', 'Reverse proxy settings updated', 'success');
  17090. await loadReverseProxy(false);
  17091. } catch (err) {
  17092. showToast('Error', err.message, 'error');
  17093. }
  17094. }
  17095. // ==================== SD-WAN Controller ====================
  17096. async function loadSDWAN(manual = false) {
  17097. try {
  17098. const [groupsRes, telemetryRes] = await Promise.all([
  17099. fetch(`${API_BASE}/sdwan/groups`),
  17100. fetch(`${API_BASE}/sdwan/telemetry`)
  17101. ]);
  17102. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17103. state.sdwanGroups = await groupsRes.json() || [];
  17104. if (telemetryRes.ok) {
  17105. state.sdwanTelemetry = await telemetryRes.json() || {};
  17106. }
  17107. renderSDWANGroups(state.sdwanGroups);
  17108. renderSDWANMembers(state.sdwanGroups);
  17109. updateSDWANMetrics(state.sdwanTelemetry);
  17110. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17111. } catch (err) {
  17112. console.error('loadSDWAN error:', err);
  17113. if (manual) showToast('Error', err.message, 'error');
  17114. }
  17115. }
  17116. function updateSDWANMetrics(telemetry) {
  17117. const groups = state.sdwanGroups || [];
  17118. const t = telemetry || {};
  17119. const badge = document.getElementById('badge-sdwan-count');
  17120. if (badge) badge.textContent = groups.length;
  17121. const metricGroups = document.getElementById('sdwan-metric-groups');
  17122. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17123. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17124. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17125. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17126. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17127. const metricDown = document.getElementById('sdwan-metric-down');
  17128. if (metricDown) metricDown.textContent = t.down_members || 0;
  17129. }
  17130. function renderSDWANGroups(groups) {
  17131. const tbody = document.getElementById('sdwan-groups-table-body');
  17132. if (!tbody) return;
  17133. if (!groups || groups.length === 0) {
  17134. 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>';
  17135. return;
  17136. }
  17137. tbody.innerHTML = groups.map(g => {
  17138. const isEnabled = g.disabled !== true;
  17139. const members = g.members || [];
  17140. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17141. // Build distribution progress bar
  17142. let distHtml = '';
  17143. if (members.length === 0) {
  17144. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17145. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17146. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17147. const segments = members.map((m, idx) => {
  17148. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17149. const col = colors[idx % colors.length];
  17150. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17151. }).join('');
  17152. const labels = members.map((m, idx) => {
  17153. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17154. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17155. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17156. }).join('');
  17157. distHtml = `
  17158. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17159. <div class="flex flex-wrap">${labels}</div>
  17160. `;
  17161. } else if (g.mode === 'lowest-latency') {
  17162. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17163. } else if (g.mode === 'lowest-loss') {
  17164. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17165. } else if (g.mode === 'failover') {
  17166. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17167. }
  17168. let modeBadge = '';
  17169. switch (g.mode) {
  17170. case 'weighted':
  17171. 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>';
  17172. break;
  17173. case 'pcc':
  17174. 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>';
  17175. break;
  17176. case 'lowest-latency':
  17177. 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>';
  17178. break;
  17179. case 'lowest-loss':
  17180. 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>';
  17181. break;
  17182. case 'failover':
  17183. 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>';
  17184. break;
  17185. default:
  17186. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17187. }
  17188. const autoNatBadge = g.auto_nat
  17189. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17190. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17191. return `
  17192. <tr class="hover:bg-slate-800/40 transition">
  17193. <td class="py-3 px-4">
  17194. <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'}">
  17195. <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>
  17196. </button>
  17197. </td>
  17198. <td class="py-3 px-4">
  17199. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17200. <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>
  17201. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17202. </div>
  17203. </td>
  17204. <td class="py-3 px-4">${modeBadge}</td>
  17205. <td class="py-3 px-4">${distHtml}</td>
  17206. <td class="py-3 px-4">
  17207. <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>
  17208. </td>
  17209. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17210. <td class="py-3 px-4">${autoNatBadge}</td>
  17211. <td class="py-3 px-4 text-right">
  17212. <div class="flex items-center justify-end gap-1.5">
  17213. <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">
  17214. <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>
  17215. </button>
  17216. <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">
  17217. <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>
  17218. </button>
  17219. <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">
  17220. <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>
  17221. </button>
  17222. </div>
  17223. </td>
  17224. </tr>
  17225. `;
  17226. }).join('');
  17227. }
  17228. function renderSDWANMembers(groups) {
  17229. const tbody = document.getElementById('sdwan-members-table-body');
  17230. if (!tbody) return;
  17231. const allMembers = [];
  17232. (groups || []).forEach(g => {
  17233. (g.members || []).forEach(m => {
  17234. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17235. });
  17236. });
  17237. if (allMembers.length === 0) {
  17238. 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>';
  17239. return;
  17240. }
  17241. tbody.innerHTML = allMembers.map(m => {
  17242. const isEnabled = m.disabled !== true;
  17243. 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>';
  17244. if (!isEnabled) {
  17245. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17246. } else if (m.status === 'DEGRADED') {
  17247. 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>';
  17248. } else if (m.status === 'DOWN') {
  17249. 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>';
  17250. }
  17251. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17252. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17253. return `
  17254. <tr class="hover:bg-slate-800/40 transition">
  17255. <td class="py-3 px-4">
  17256. <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'}">
  17257. <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>
  17258. </button>
  17259. </td>
  17260. <td class="py-3 px-4">
  17261. <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>
  17262. </td>
  17263. <td class="py-3 px-4">
  17264. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17265. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17266. </td>
  17267. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17268. <td class="py-3 px-4">
  17269. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17270. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17271. </td>
  17272. <td class="py-3 px-4">${statusBadge}</td>
  17273. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17274. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17275. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17276. </td>
  17277. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17278. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17279. </td>
  17280. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17281. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17282. </td>
  17283. <td class="py-3 px-4 text-right">
  17284. <div class="flex items-center justify-end gap-1.5">
  17285. <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">
  17286. <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>
  17287. </button>
  17288. <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">
  17289. <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>
  17290. </button>
  17291. </div>
  17292. </td>
  17293. </tr>
  17294. `;
  17295. }).join('');
  17296. }
  17297. // Modal handling for SD-WAN Groups
  17298. function openAddSDWANGroupModal() {
  17299. const modal = document.getElementById('modal-sdwan-group');
  17300. if (!modal) return;
  17301. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17302. document.getElementById('sdwan-group-id').value = '';
  17303. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17304. document.getElementById('sdwan-group-name').disabled = false;
  17305. document.getElementById('sdwan-group-mode').value = 'weighted';
  17306. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17307. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17308. document.getElementById('sdwan-group-probe-interval').value = 3;
  17309. document.getElementById('sdwan-group-auto-nat').checked = true;
  17310. document.getElementById('sdwan-group-comment').value = '';
  17311. modal.classList.remove('hidden');
  17312. }
  17313. function openEditSDWANGroupModal(id) {
  17314. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17315. if (!group) return;
  17316. const modal = document.getElementById('modal-sdwan-group');
  17317. if (!modal) return;
  17318. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17319. document.getElementById('sdwan-group-id').value = group.id;
  17320. document.getElementById('sdwan-group-name').value = group.name;
  17321. document.getElementById('sdwan-group-name').disabled = true;
  17322. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17323. if (group.mode === 'pcc') {
  17324. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17325. } else {
  17326. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17327. }
  17328. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17329. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17330. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17331. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17332. modal.classList.remove('hidden');
  17333. }
  17334. function closeSDWANGroupModal() {
  17335. const modal = document.getElementById('modal-sdwan-group');
  17336. if (modal) modal.classList.add('hidden');
  17337. }
  17338. function onSDWANModeChange() {
  17339. const mode = document.getElementById('sdwan-group-mode').value;
  17340. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17341. if (pccContainer) {
  17342. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17343. else pccContainer.classList.add('hidden');
  17344. }
  17345. }
  17346. async function saveSDWANGroup(event) {
  17347. event.preventDefault();
  17348. const id = document.getElementById('sdwan-group-id').value;
  17349. const name = document.getElementById('sdwan-group-name').value.trim();
  17350. const mode = document.getElementById('sdwan-group-mode').value;
  17351. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17352. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17353. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17354. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17355. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17356. const payload = {
  17357. id: id || undefined,
  17358. name,
  17359. mode,
  17360. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17361. probe_interval: probeInterval,
  17362. auto_nat: autoNAT,
  17363. comment,
  17364. members: existing ? existing.members : undefined
  17365. };
  17366. try {
  17367. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17368. method: 'POST',
  17369. headers: { 'Content-Type': 'application/json' },
  17370. body: JSON.stringify(payload)
  17371. });
  17372. if (!res.ok) {
  17373. const err = await res.json().catch(() => ({}));
  17374. throw new Error(err.message || 'Failed to save SD-WAN group');
  17375. }
  17376. closeSDWANGroupModal();
  17377. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17378. await loadSDWAN(false);
  17379. } catch (err) {
  17380. showToast('Error', err.message, 'error');
  17381. }
  17382. }
  17383. async function toggleSDWANGroupState(id, currentState) {
  17384. try {
  17385. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17386. method: 'POST',
  17387. headers: { 'Content-Type': 'application/json' },
  17388. body: JSON.stringify({ disabled: currentState })
  17389. });
  17390. if (!res.ok) throw new Error('Failed to update group state');
  17391. await loadSDWAN(false);
  17392. } catch (err) {
  17393. showToast('Error', err.message, 'error');
  17394. }
  17395. }
  17396. async function deleteSDWANGroup(id) {
  17397. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17398. const name = group ? group.name : id;
  17399. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17400. try {
  17401. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17402. method: 'DELETE'
  17403. });
  17404. if (!res.ok) {
  17405. const err = await res.json().catch(() => ({}));
  17406. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17407. }
  17408. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17409. await loadSDWAN(false);
  17410. } catch (err) {
  17411. showToast('Error', err.message, 'error');
  17412. }
  17413. }
  17414. // Modal handling for SD-WAN Members
  17415. function populateSDWANGroupsSelect(selectedId = '') {
  17416. const sel = document.getElementById('sdwan-member-group-id');
  17417. if (!sel) return;
  17418. sel.innerHTML = '';
  17419. (state.sdwanGroups || []).forEach(g => {
  17420. const opt = document.createElement('option');
  17421. opt.value = g.id;
  17422. opt.textContent = `${g.name} (${g.mode})`;
  17423. if (g.id === selectedId) opt.selected = true;
  17424. sel.appendChild(opt);
  17425. });
  17426. }
  17427. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17428. const sel = document.getElementById('sdwan-member-interface');
  17429. if (!sel) return;
  17430. sel.innerHTML = '';
  17431. (state.interfaces || []).forEach(i => {
  17432. const opt = document.createElement('option');
  17433. opt.value = i.name;
  17434. opt.textContent = `${i.name} (${i.role || i.type})`;
  17435. if (i.name === selectedVal) opt.selected = true;
  17436. sel.appendChild(opt);
  17437. });
  17438. }
  17439. function openAddSDWANMemberModal(defaultGroupId = null) {
  17440. const modal = document.getElementById('modal-sdwan-member');
  17441. if (!modal) return;
  17442. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17443. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17444. return;
  17445. }
  17446. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17447. document.getElementById('sdwan-member-id').value = '';
  17448. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17449. populateSDWANMemberInterfaceSelect();
  17450. document.getElementById('sdwan-member-gateway').value = '';
  17451. document.getElementById('sdwan-member-weight').value = 50;
  17452. document.getElementById('sdwan-member-priority').value = 1;
  17453. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17454. document.getElementById('sdwan-member-max-lat').value = 250;
  17455. document.getElementById('sdwan-member-max-loss').value = 20;
  17456. document.getElementById('sdwan-member-comment').value = '';
  17457. modal.classList.remove('hidden');
  17458. }
  17459. function openEditSDWANMemberModal(groupId, memberId) {
  17460. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17461. if (!group) return;
  17462. const member = (group.members || []).find(m => m.id === memberId);
  17463. if (!member) return;
  17464. const modal = document.getElementById('modal-sdwan-member');
  17465. if (!modal) return;
  17466. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17467. document.getElementById('sdwan-member-id').value = member.id;
  17468. populateSDWANGroupsSelect(group.id);
  17469. document.getElementById('sdwan-member-group-id').disabled = true;
  17470. populateSDWANMemberInterfaceSelect(member.interface);
  17471. document.getElementById('sdwan-member-interface').disabled = true;
  17472. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17473. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17474. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17475. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17476. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17477. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17478. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17479. modal.classList.remove('hidden');
  17480. }
  17481. function closeSDWANMemberModal() {
  17482. const modal = document.getElementById('modal-sdwan-member');
  17483. if (modal) {
  17484. document.getElementById('sdwan-member-group-id').disabled = false;
  17485. document.getElementById('sdwan-member-interface').disabled = false;
  17486. modal.classList.add('hidden');
  17487. }
  17488. }
  17489. async function saveSDWANMember(event) {
  17490. event.preventDefault();
  17491. const id = document.getElementById('sdwan-member-id').value;
  17492. let groupId = document.getElementById('sdwan-member-group-id').value;
  17493. let iface = document.getElementById('sdwan-member-interface').value;
  17494. // In edit mode with disabled selects, fallback to existing member data if needed
  17495. if (id) {
  17496. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17497. if (existingGroup) {
  17498. if (!groupId) groupId = existingGroup.id;
  17499. const mem = (existingGroup.members || []).find(m => m.id === id);
  17500. if (mem && !iface) iface = mem.interface;
  17501. }
  17502. }
  17503. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17504. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17505. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17506. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17507. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17508. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17509. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17510. const payload = {
  17511. id: id || undefined,
  17512. interface: iface,
  17513. gateway,
  17514. weight,
  17515. priority,
  17516. target_probe: targetProbe,
  17517. max_latency: maxLatency,
  17518. max_loss: maxLoss,
  17519. comment
  17520. };
  17521. try {
  17522. const method = id ? 'PUT' : 'POST';
  17523. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17524. method,
  17525. headers: { 'Content-Type': 'application/json' },
  17526. body: JSON.stringify(payload)
  17527. });
  17528. if (!res.ok) {
  17529. const err = await res.json().catch(() => ({}));
  17530. throw new Error(err.message || 'Failed to save member link');
  17531. }
  17532. closeSDWANMemberModal();
  17533. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17534. await loadSDWAN(false);
  17535. } catch (err) {
  17536. showToast('Error', err.message, 'error');
  17537. }
  17538. }
  17539. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17540. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17541. if (!group) return;
  17542. const member = (group.members || []).find(m => m.id === memberId);
  17543. if (!member) return;
  17544. const payload = {
  17545. ...member,
  17546. disabled: currentState
  17547. };
  17548. try {
  17549. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17550. method: 'PUT',
  17551. headers: { 'Content-Type': 'application/json' },
  17552. body: JSON.stringify(payload)
  17553. });
  17554. if (!res.ok) throw new Error('Failed to update member state');
  17555. await loadSDWAN(false);
  17556. } catch (err) {
  17557. showToast('Error', err.message, 'error');
  17558. }
  17559. }
  17560. async function deleteSDWANMember(groupId, iface) {
  17561. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17562. try {
  17563. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17564. method: 'DELETE'
  17565. });
  17566. if (!res.ok) {
  17567. const err = await res.json().catch(() => ({}));
  17568. throw new Error(err.message || 'Failed to remove member link');
  17569. }
  17570. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17571. await loadSDWAN(false);
  17572. } catch (err) {
  17573. showToast('Error', err.message, 'error');
  17574. }
  17575. }
  17576. // ==============================================================================
  17577. // DYNAMIC ROUTING: RIP MODULE
  17578. // ==============================================================================
  17579. state.ripInstances = [];
  17580. state.ripInterfaces = [];
  17581. state.ripNeighborsLive = [];
  17582. state.ripRoutes = [];
  17583. state.selectedRipRow = {};
  17584. state.activeRipTab = 'instances';
  17585. function switchRipTab(tab) {
  17586. state.activeRipTab = tab;
  17587. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17588. const pane = document.getElementById(`rip-pane-${t}`);
  17589. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17590. if (pane) {
  17591. if (t === tab) pane.classList.remove('hidden');
  17592. else pane.classList.add('hidden');
  17593. }
  17594. if (btn) {
  17595. if (t === tab) {
  17596. 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';
  17597. } else {
  17598. 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';
  17599. }
  17600. }
  17601. });
  17602. }
  17603. function selectRipRow(tab, id) {
  17604. if (!state.selectedRipRow) state.selectedRipRow = {};
  17605. state.selectedRipRow[tab] = id;
  17606. if (tab === 'instances') {
  17607. renderRipInstances();
  17608. const btnEn = document.getElementById('btn-rip-inst-enable');
  17609. const btnDis = document.getElementById('btn-rip-inst-disable');
  17610. const btnRem = document.getElementById('btn-rip-inst-remove');
  17611. if (btnEn) btnEn.disabled = false;
  17612. if (btnDis) btnDis.disabled = false;
  17613. if (btnRem) btnRem.disabled = false;
  17614. } else if (tab === 'interfaces') {
  17615. renderRipInterfaces();
  17616. const btnEn = document.getElementById('btn-rip-iface-enable');
  17617. const btnDis = document.getElementById('btn-rip-iface-disable');
  17618. const btnRem = document.getElementById('btn-rip-iface-remove');
  17619. if (btnEn) btnEn.disabled = false;
  17620. if (btnDis) btnDis.disabled = false;
  17621. if (btnRem) btnRem.disabled = false;
  17622. }
  17623. }
  17624. function renderRipInstances() {
  17625. const tbody = document.getElementById('rip-instances-table-body');
  17626. if (!tbody) return;
  17627. const countEl = document.getElementById('rip-instances-footer-count');
  17628. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17629. let list = state.ripInstances || [];
  17630. if (filter) {
  17631. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17632. }
  17633. if (countEl) countEl.innerText = list.length;
  17634. const selId = state.selectedRipRow?.instances;
  17635. tbody.innerHTML = list.map((inst, idx) => {
  17636. const isSel = inst.id === selId;
  17637. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17638. const flagD = inst.disabled
  17639. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  17640. : (inst.running
  17641. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  17642. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  17643. const redist = [];
  17644. if (inst.redistribute_connected) redist.push('conn');
  17645. if (inst.redistribute_static) redist.push('static');
  17646. if (inst.redistribute_bgp) redist.push('bgp');
  17647. if (inst.redistribute_ospf) redist.push('ospf');
  17648. if (inst.redistribute_default) redist.push('default');
  17649. return `
  17650. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17651. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17652. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17653. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17654. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17655. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17656. </td>
  17657. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${escapeHtml(inst.version || 'rip2')}</td>
  17658. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17659. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17660. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17661. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17662. </tr>
  17663. `;
  17664. }).join('');
  17665. }
  17666. function renderRipInterfaces() {
  17667. const tbody = document.getElementById('rip-interfaces-table-body');
  17668. if (!tbody) return;
  17669. const countEl = document.getElementById('rip-interfaces-footer-count');
  17670. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17671. let list = state.ripInterfaces || [];
  17672. if (filter) {
  17673. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17674. }
  17675. if (countEl) countEl.innerText = list.length;
  17676. const selId = state.selectedRipRow?.interfaces;
  17677. tbody.innerHTML = list.map((iface, idx) => {
  17678. const isSel = iface.id === selId;
  17679. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17680. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17681. return `
  17682. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17683. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17684. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17685. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17686. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17687. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17688. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17689. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17690. <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>
  17691. </tr>
  17692. `;
  17693. }).join('');
  17694. }
  17695. function renderRipNeighbors() {
  17696. const tbody = document.getElementById('rip-neighbors-table-body');
  17697. if (!tbody) return;
  17698. const countEl = document.getElementById('rip-neighbors-footer-count');
  17699. const list = state.ripNeighborsLive || [];
  17700. if (countEl) countEl.innerText = list.length;
  17701. tbody.innerHTML = list.map((nbr, idx) => `
  17702. <tr class="hover:bg-[#1a2636] text-slate-300">
  17703. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17704. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17705. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17706. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17707. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17708. </tr>
  17709. `).join('');
  17710. }
  17711. function renderRipRoutes() {
  17712. const tbody = document.getElementById('rip-routes-table-body');
  17713. if (!tbody) return;
  17714. const countEl = document.getElementById('rip-routes-footer-count');
  17715. const list = state.ripRoutes || [];
  17716. if (countEl) countEl.innerText = list.length;
  17717. tbody.innerHTML = list.map((r, idx) => `
  17718. <tr class="hover:bg-[#1a2636] text-slate-300">
  17719. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17720. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17721. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17722. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17723. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17724. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17725. </tr>
  17726. `).join('');
  17727. }
  17728. function openRipInstanceModal() {
  17729. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17730. document.getElementById('modal-rip-instance-id').value = '';
  17731. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17732. document.getElementById('modal-rip-instance-version').value = 'rip2';
  17733. document.getElementById('modal-rip-instance-update').value = '30';
  17734. document.getElementById('modal-rip-instance-timeout').value = '180';
  17735. document.getElementById('modal-rip-instance-garbage').value = '120';
  17736. document.getElementById('modal-rip-instance-metric').value = '1';
  17737. document.getElementById('modal-rip-instance-comment').value = '';
  17738. document.getElementById('modal-rip-instance-enabled').checked = true;
  17739. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17740. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17741. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17742. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17743. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17744. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17745. }
  17746. function openEditRipInstanceModal(id) {
  17747. const inst = (state.ripInstances || []).find(i => i.id === id);
  17748. if (!inst) return;
  17749. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17750. document.getElementById('modal-rip-instance-id').value = inst.id;
  17751. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17752. document.getElementById('modal-rip-instance-version').value = inst.version || 'rip2';
  17753. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17754. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17755. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17756. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17757. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17758. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17759. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17760. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17761. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17762. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17763. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17764. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17765. }
  17766. function closeRipInstanceModal() {
  17767. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17768. }
  17769. async function submitRipInstance(e) {
  17770. e.preventDefault();
  17771. const id = document.getElementById('modal-rip-instance-id').value;
  17772. const payload = {
  17773. id: id || undefined,
  17774. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17775. version: document.getElementById('modal-rip-instance-version').value,
  17776. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17777. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17778. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17779. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17780. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17781. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17782. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17783. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17784. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17785. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17786. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17787. };
  17788. try {
  17789. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17790. method: 'POST',
  17791. headers: { 'Content-Type': 'application/json' },
  17792. body: JSON.stringify(payload)
  17793. });
  17794. if (!res.ok) throw new Error(await res.text());
  17795. closeRipInstanceModal();
  17796. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17797. await loadDynamicRouting(false);
  17798. } catch (err) {
  17799. showToast('Error', err.message, 'error');
  17800. }
  17801. }
  17802. async function enableSelectedRipInstance() {
  17803. const id = state.selectedRipRow?.instances;
  17804. if (!id) return;
  17805. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17806. await loadDynamicRouting(false);
  17807. }
  17808. async function disableSelectedRipInstance() {
  17809. const id = state.selectedRipRow?.instances;
  17810. if (!id) return;
  17811. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17812. await loadDynamicRouting(false);
  17813. }
  17814. async function removeSelectedRipInstance() {
  17815. const id = state.selectedRipRow?.instances;
  17816. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17817. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17818. state.selectedRipRow.instances = null;
  17819. await loadDynamicRouting(false);
  17820. }
  17821. function openRipInterfaceModal() {
  17822. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17823. document.getElementById('modal-rip-iface-id').value = '';
  17824. const dl = document.getElementById('rip-iface-datalist');
  17825. if (dl) {
  17826. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17827. }
  17828. const instSel = document.getElementById('modal-rip-iface-instance');
  17829. if (instSel && instSel.tagName === 'SELECT') {
  17830. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17831. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17832. }
  17833. document.getElementById('modal-rip-iface-pattern').value = '*';
  17834. if (instSel) instSel.value = (state.ripInstances && state.ripInstances.length > 0) ? state.ripInstances[0].name : 'default';
  17835. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17836. document.getElementById('modal-rip-iface-metric').value = '1';
  17837. document.getElementById('modal-rip-iface-comment').value = '';
  17838. document.getElementById('modal-rip-iface-enabled').checked = true;
  17839. document.getElementById('modal-rip-iface-passive').checked = false;
  17840. document.getElementById('modal-rip-iface-bfd').checked = false;
  17841. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17842. }
  17843. function openEditRipInterfaceModal(id) {
  17844. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17845. if (!iface) return;
  17846. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17847. document.getElementById('modal-rip-iface-id').value = iface.id;
  17848. const dl = document.getElementById('rip-iface-datalist');
  17849. if (dl) {
  17850. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17851. }
  17852. const instSel = document.getElementById('modal-rip-iface-instance');
  17853. if (instSel && instSel.tagName === 'SELECT') {
  17854. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17855. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17856. instSel.value = iface.instance || 'default';
  17857. } else if (instSel) {
  17858. instSel.value = iface.instance || '';
  17859. }
  17860. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '*';
  17861. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17862. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17863. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17864. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17865. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17866. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17867. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17868. }
  17869. function closeRipInterfaceModal() {
  17870. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17871. }
  17872. async function submitRipInterface(e) {
  17873. e.preventDefault();
  17874. const id = document.getElementById('modal-rip-iface-id').value;
  17875. const payload = {
  17876. id: id || undefined,
  17877. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17878. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17879. mode: document.getElementById('modal-rip-iface-mode').value,
  17880. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17881. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17882. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17883. passive: document.getElementById('modal-rip-iface-passive').checked,
  17884. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17885. };
  17886. try {
  17887. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17888. method: 'POST',
  17889. headers: { 'Content-Type': 'application/json' },
  17890. body: JSON.stringify(payload)
  17891. });
  17892. if (!res.ok) throw new Error(await res.text());
  17893. closeRipInterfaceModal();
  17894. showToast('Saved', `RIP interface template saved`, 'success');
  17895. await loadDynamicRouting(false);
  17896. } catch (err) {
  17897. showToast('Error', err.message, 'error');
  17898. }
  17899. }
  17900. async function enableSelectedRipInterface() {
  17901. const id = state.selectedRipRow?.interfaces;
  17902. if (!id) return;
  17903. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17904. await loadDynamicRouting(false);
  17905. }
  17906. async function disableSelectedRipInterface() {
  17907. const id = state.selectedRipRow?.interfaces;
  17908. if (!id) return;
  17909. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17910. await loadDynamicRouting(false);
  17911. }
  17912. async function removeSelectedRipInterface() {
  17913. const id = state.selectedRipRow?.interfaces;
  17914. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17915. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17916. state.selectedRipRow.interfaces = null;
  17917. await loadDynamicRouting(false);
  17918. }
  17919. // ==============================================================================
  17920. // DYNAMIC ROUTING: BFD MODULE
  17921. // ==============================================================================
  17922. state.bfdInstance = null;
  17923. state.bfdInterfaces = [];
  17924. state.bfdNeighbors = [];
  17925. state.bfdSessions = [];
  17926. state.selectedBfdRow = {};
  17927. state.activeBfdTab = 'config';
  17928. function switchBfdTab(tab) {
  17929. state.activeBfdTab = tab;
  17930. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  17931. const pane = document.getElementById(`bfd-pane-${t}`);
  17932. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  17933. if (pane) {
  17934. if (t === tab) pane.classList.remove('hidden');
  17935. else pane.classList.add('hidden');
  17936. }
  17937. if (btn) {
  17938. if (t === tab) {
  17939. 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';
  17940. } else {
  17941. 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';
  17942. }
  17943. }
  17944. });
  17945. }
  17946. function selectBfdRow(tab, id) {
  17947. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  17948. state.selectedBfdRow[tab] = id;
  17949. if (tab === 'interfaces') {
  17950. renderBfdInterfaces();
  17951. const btnEn = document.getElementById('btn-bfd-iface-enable');
  17952. const btnDis = document.getElementById('btn-bfd-iface-disable');
  17953. const btnRem = document.getElementById('btn-bfd-iface-remove');
  17954. if (btnEn) btnEn.disabled = false;
  17955. if (btnDis) btnDis.disabled = false;
  17956. if (btnRem) btnRem.disabled = false;
  17957. } else if (tab === 'peers') {
  17958. renderBfdPeers();
  17959. const btnEn = document.getElementById('btn-bfd-peer-enable');
  17960. const btnDis = document.getElementById('btn-bfd-peer-disable');
  17961. const btnRem = document.getElementById('btn-bfd-peer-remove');
  17962. if (btnEn) btnEn.disabled = false;
  17963. if (btnDis) btnDis.disabled = false;
  17964. if (btnRem) btnRem.disabled = false;
  17965. }
  17966. }
  17967. function renderBfdConfig() {
  17968. const inst = state.bfdInstance;
  17969. const pill = document.getElementById('bfd-live-status-pill');
  17970. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  17971. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  17972. const peerStat = document.getElementById('bfd-stat-peers');
  17973. const sessStat = document.getElementById('bfd-stat-sessions');
  17974. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  17975. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  17976. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  17977. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  17978. if (!inst || inst.disabled || !isEnabled) {
  17979. if (pill) {
  17980. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  17981. pill.innerText = 'DISABLED';
  17982. }
  17983. if (toggleBtn) {
  17984. toggleBtn.innerText = 'Enable BFD';
  17985. 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';
  17986. }
  17987. } else {
  17988. if (pill) {
  17989. if (inst.running) {
  17990. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-emerald-950 text-emerald-300 border border-emerald-800/60 font-semibold';
  17991. pill.innerText = 'RUNNING (ACTIVE)';
  17992. } else {
  17993. 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';
  17994. pill.innerText = 'CONFIGURED';
  17995. }
  17996. }
  17997. if (toggleBtn) {
  17998. toggleBtn.innerText = 'Disable BFD';
  17999. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  18000. }
  18001. }
  18002. }
  18003. async function toggleBfdGlobalState() {
  18004. const current = state.bfdInstance;
  18005. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  18006. const newEnabled = !isCurrentlyEnabled;
  18007. const newDisabled = !newEnabled;
  18008. try {
  18009. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  18010. method: 'POST',
  18011. headers: { 'Content-Type': 'application/json' },
  18012. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  18013. });
  18014. if (!res.ok) throw new Error(await res.text());
  18015. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  18016. await loadDynamicRouting(false);
  18017. } catch (err) {
  18018. showToast('Error', err.message, 'error');
  18019. }
  18020. }
  18021. function renderBfdInterfaces() {
  18022. const tbody = document.getElementById('bfd-interfaces-table-body');
  18023. if (!tbody) return;
  18024. const countEl = document.getElementById('bfd-interfaces-footer-count');
  18025. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  18026. let list = state.bfdInterfaces || [];
  18027. if (filter) {
  18028. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18029. }
  18030. if (countEl) countEl.innerText = list.length;
  18031. const selId = state.selectedBfdRow?.interfaces;
  18032. tbody.innerHTML = list.map((iface, idx) => {
  18033. const isSel = iface.id === selId;
  18034. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18035. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18036. return `
  18037. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  18038. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18039. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18040. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18041. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18042. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  18043. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18044. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18045. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18046. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18047. </tr>
  18048. `;
  18049. }).join('');
  18050. }
  18051. function renderBfdPeers() {
  18052. const tbody = document.getElementById('bfd-peers-table-body');
  18053. if (!tbody) return;
  18054. const countEl = document.getElementById('bfd-peers-footer-count');
  18055. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18056. let list = state.bfdNeighbors || [];
  18057. if (filter) {
  18058. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18059. }
  18060. if (countEl) countEl.innerText = list.length;
  18061. const selId = state.selectedBfdRow?.peers;
  18062. tbody.innerHTML = list.map((p, idx) => {
  18063. const isSel = p.id === selId;
  18064. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18065. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18066. return `
  18067. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18068. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18069. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18070. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18071. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18072. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18073. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18074. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18075. </tr>
  18076. `;
  18077. }).join('');
  18078. }
  18079. function renderBfdSessions() {
  18080. const tbody = document.getElementById('bfd-sessions-table-body');
  18081. if (!tbody) return;
  18082. const countEl = document.getElementById('bfd-sessions-footer-count');
  18083. const list = state.bfdSessions || [];
  18084. if (countEl) countEl.innerText = list.length;
  18085. tbody.innerHTML = list.map((s, idx) => {
  18086. const isUp = (s.state || '').toLowerCase() === 'up';
  18087. const stateBadge = isUp
  18088. ? '<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>'
  18089. : `<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>`;
  18090. return `
  18091. <tr class="hover:bg-[#1a2636] text-slate-300">
  18092. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18093. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18094. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18095. <td class="py-1.5 px-3">${stateBadge}</td>
  18096. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18097. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18098. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18099. </tr>
  18100. `;
  18101. }).join('');
  18102. }
  18103. function openBfdInterfaceModal() {
  18104. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18105. document.getElementById('modal-bfd-iface-id').value = '';
  18106. const dl = document.getElementById('bfd-iface-datalist');
  18107. if (dl) {
  18108. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18109. }
  18110. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18111. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18112. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18113. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18114. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18115. document.getElementById('modal-bfd-iface-comment').value = '';
  18116. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18117. document.getElementById('modal-bfd-iface-passive').checked = false;
  18118. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18119. }
  18120. function openEditBfdInterfaceModal(id) {
  18121. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18122. if (!iface) return;
  18123. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18124. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18125. const dl = document.getElementById('bfd-iface-datalist');
  18126. if (dl) {
  18127. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18128. }
  18129. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18130. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18131. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18132. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18133. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18134. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18135. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18136. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18137. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18138. }
  18139. function closeBfdInterfaceModal() {
  18140. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18141. }
  18142. async function submitBfdInterface(e) {
  18143. e.preventDefault();
  18144. const id = document.getElementById('modal-bfd-iface-id').value;
  18145. const payload = {
  18146. id: id || undefined,
  18147. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18148. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18149. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18150. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18151. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18152. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18153. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18154. passive: document.getElementById('modal-bfd-iface-passive').checked
  18155. };
  18156. try {
  18157. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18158. method: 'POST',
  18159. headers: { 'Content-Type': 'application/json' },
  18160. body: JSON.stringify(payload)
  18161. });
  18162. if (!res.ok) throw new Error(await res.text());
  18163. closeBfdInterfaceModal();
  18164. showToast('Saved', `BFD profile saved`, 'success');
  18165. await loadDynamicRouting(false);
  18166. } catch (err) {
  18167. showToast('Error', err.message, 'error');
  18168. }
  18169. }
  18170. async function enableSelectedBfdInterface() {
  18171. const id = state.selectedBfdRow?.interfaces;
  18172. if (!id) return;
  18173. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18174. await loadDynamicRouting(false);
  18175. }
  18176. async function disableSelectedBfdInterface() {
  18177. const id = state.selectedBfdRow?.interfaces;
  18178. if (!id) return;
  18179. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18180. await loadDynamicRouting(false);
  18181. }
  18182. async function removeSelectedBfdInterface() {
  18183. const id = state.selectedBfdRow?.interfaces;
  18184. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18185. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18186. state.selectedBfdRow.interfaces = null;
  18187. await loadDynamicRouting(false);
  18188. }
  18189. function openBfdPeerModal() {
  18190. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18191. document.getElementById('modal-bfd-peer-id').value = '';
  18192. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18193. if (dlPeer) {
  18194. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18195. }
  18196. document.getElementById('modal-bfd-peer-address').value = '';
  18197. document.getElementById('modal-bfd-peer-interface').value = '';
  18198. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18199. if (localAddrEl) localAddrEl.value = '';
  18200. document.getElementById('modal-bfd-peer-comment').value = '';
  18201. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18202. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18203. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18204. }
  18205. function openEditBfdPeerModal(id) {
  18206. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18207. if (!p) return;
  18208. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18209. document.getElementById('modal-bfd-peer-id').value = p.id;
  18210. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18211. if (dlPeer) {
  18212. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18213. }
  18214. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18215. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18216. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18217. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18218. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18219. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18220. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18221. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18222. }
  18223. function closeBfdPeerModal() {
  18224. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18225. }
  18226. async function submitBfdPeer(e) {
  18227. e.preventDefault();
  18228. const id = document.getElementById('modal-bfd-peer-id').value;
  18229. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18230. const payload = {
  18231. id: id || undefined,
  18232. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18233. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18234. local_address: localAddr,
  18235. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18236. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18237. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18238. };
  18239. try {
  18240. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18241. method: 'POST',
  18242. headers: { 'Content-Type': 'application/json' },
  18243. body: JSON.stringify(payload)
  18244. });
  18245. if (!res.ok) throw new Error(await res.text());
  18246. closeBfdPeerModal();
  18247. showToast('Saved', `BFD peer saved`, 'success');
  18248. await loadDynamicRouting(false);
  18249. } catch (err) {
  18250. showToast('Error', err.message, 'error');
  18251. }
  18252. }
  18253. async function enableSelectedBfdPeer() {
  18254. const id = state.selectedBfdRow?.peers;
  18255. if (!id) return;
  18256. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18257. if (!p) return;
  18258. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18259. await loadDynamicRouting(false);
  18260. }
  18261. async function disableSelectedBfdPeer() {
  18262. const id = state.selectedBfdRow?.peers;
  18263. if (!id) return;
  18264. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18265. if (!p) return;
  18266. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18267. await loadDynamicRouting(false);
  18268. }
  18269. async function removeSelectedBfdPeer() {
  18270. const id = state.selectedBfdRow?.peers;
  18271. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18272. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18273. state.selectedBfdRow.peers = null;
  18274. await loadDynamicRouting(false);
  18275. }
  18276. // ==============================================================================
  18277. // DYNAMIC ROUTING: BABEL MODULE
  18278. // ==============================================================================
  18279. state.babelInstances = [];
  18280. state.babelInterfaces = [];
  18281. state.babelInterfacesLive = [];
  18282. state.babelNeighbors = [];
  18283. state.babelRoutes = [];
  18284. state.selectedBabelRow = {};
  18285. state.activeBabelTab = 'instances';
  18286. function switchBabelTab(tab) {
  18287. state.activeBabelTab = tab;
  18288. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18289. const pane = document.getElementById(`babel-pane-${t}`);
  18290. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18291. if (pane) {
  18292. if (t === tab) pane.classList.remove('hidden');
  18293. else pane.classList.add('hidden');
  18294. }
  18295. if (btn) {
  18296. if (t === tab) {
  18297. 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';
  18298. } else {
  18299. 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';
  18300. }
  18301. }
  18302. });
  18303. }
  18304. function selectBabelRow(tab, id) {
  18305. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18306. state.selectedBabelRow[tab] = id;
  18307. if (tab === 'instances') {
  18308. renderBabelInstances();
  18309. const btnEn = document.getElementById('btn-babel-inst-enable');
  18310. const btnDis = document.getElementById('btn-babel-inst-disable');
  18311. const btnRem = document.getElementById('btn-babel-inst-remove');
  18312. if (btnEn) btnEn.disabled = false;
  18313. if (btnDis) btnDis.disabled = false;
  18314. if (btnRem) btnRem.disabled = false;
  18315. } else if (tab === 'interfaces') {
  18316. renderBabelInterfaces();
  18317. const btnEn = document.getElementById('btn-babel-iface-enable');
  18318. const btnDis = document.getElementById('btn-babel-iface-disable');
  18319. const btnRem = document.getElementById('btn-babel-iface-remove');
  18320. if (btnEn) btnEn.disabled = false;
  18321. if (btnDis) btnDis.disabled = false;
  18322. if (btnRem) btnRem.disabled = false;
  18323. }
  18324. }
  18325. function renderBabelInstances() {
  18326. const tbody = document.getElementById('babel-instances-table-body');
  18327. if (!tbody) return;
  18328. const countEl = document.getElementById('babel-instances-footer-count');
  18329. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18330. let list = state.babelInstances || [];
  18331. if (filter) {
  18332. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18333. }
  18334. if (countEl) countEl.innerText = list.length;
  18335. const selId = state.selectedBabelRow?.instances;
  18336. tbody.innerHTML = list.map((inst, idx) => {
  18337. const isSel = inst.id === selId;
  18338. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18339. const flagD = inst.disabled
  18340. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18341. : (inst.running
  18342. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18343. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18344. const redist = [];
  18345. if (inst.redistribute_connected) redist.push('conn');
  18346. if (inst.redistribute_static) redist.push('static');
  18347. if (inst.redistribute_bgp) redist.push('bgp');
  18348. if (inst.redistribute_ospf) redist.push('ospf');
  18349. if (inst.redistribute_default) redist.push('default');
  18350. return `
  18351. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18352. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18353. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18354. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18355. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18356. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18357. </td>
  18358. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18359. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18360. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18361. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18362. </tr>
  18363. `;
  18364. }).join('');
  18365. }
  18366. function renderBabelInterfaces() {
  18367. const tbody = document.getElementById('babel-interfaces-table-body');
  18368. if (!tbody) return;
  18369. const countEl = document.getElementById('babel-interfaces-footer-count');
  18370. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18371. let list = state.babelInterfaces || [];
  18372. if (filter) {
  18373. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18374. }
  18375. if (countEl) countEl.innerText = list.length;
  18376. const selId = state.selectedBabelRow?.interfaces;
  18377. tbody.innerHTML = list.map((iface, idx) => {
  18378. const isSel = iface.id === selId;
  18379. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18380. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18381. return `
  18382. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18383. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18384. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18385. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18386. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18387. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18388. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18389. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18390. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18391. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18392. </tr>
  18393. `;
  18394. }).join('');
  18395. }
  18396. function renderBabelLiveInterfaces() {
  18397. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18398. if (!tbody) return;
  18399. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18400. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18401. let list = state.babelInterfacesLive || [];
  18402. if (filter) {
  18403. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18404. }
  18405. if (countEl) countEl.innerText = list.length;
  18406. tbody.innerHTML = list.map((iface, idx) => {
  18407. const isUp = (iface.state || '').toLowerCase() === 'up';
  18408. const stateBadge = isUp
  18409. ? '<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>'
  18410. : '<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>';
  18411. return `
  18412. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18413. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18414. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18415. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18416. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18417. <td class="py-1.5 px-3">${stateBadge}</td>
  18418. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18419. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18420. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18421. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18422. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18423. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18424. </tr>
  18425. `;
  18426. }).join('');
  18427. }
  18428. function renderBabelNeighbors() {
  18429. const tbody = document.getElementById('babel-neighbors-table-body');
  18430. if (!tbody) return;
  18431. const countEl = document.getElementById('babel-neighbors-footer-count');
  18432. const list = state.babelNeighbors || [];
  18433. if (countEl) countEl.innerText = list.length;
  18434. tbody.innerHTML = list.map((nbr, idx) => `
  18435. <tr class="hover:bg-[#1a2636] text-slate-300">
  18436. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18437. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18438. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18439. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18440. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18441. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18442. </tr>
  18443. `).join('');
  18444. }
  18445. function renderBabelRoutes() {
  18446. const tbody = document.getElementById('babel-routes-table-body');
  18447. if (!tbody) return;
  18448. const countEl = document.getElementById('babel-routes-footer-count');
  18449. const list = state.babelRoutes || [];
  18450. if (countEl) countEl.innerText = list.length;
  18451. tbody.innerHTML = list.map((r, idx) => `
  18452. <tr class="hover:bg-[#1a2636] text-slate-300">
  18453. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18454. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18455. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18456. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18457. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18458. </tr>
  18459. `).join('');
  18460. }
  18461. function openBabelInstanceModal() {
  18462. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18463. document.getElementById('modal-babel-instance-id').value = '';
  18464. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18465. document.getElementById('modal-babel-instance-routerid').value = '';
  18466. document.getElementById('modal-babel-instance-metric').value = '10';
  18467. document.getElementById('modal-babel-instance-comment').value = '';
  18468. document.getElementById('modal-babel-instance-enabled').checked = true;
  18469. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18470. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18471. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18472. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18473. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18474. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18475. }
  18476. function openEditBabelInstanceModal(id) {
  18477. const inst = (state.babelInstances || []).find(i => i.id === id);
  18478. if (!inst) return;
  18479. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18480. document.getElementById('modal-babel-instance-id').value = inst.id;
  18481. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18482. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18483. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18484. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18485. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18486. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18487. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18488. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18489. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18490. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18491. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18492. }
  18493. function closeBabelInstanceModal() {
  18494. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18495. }
  18496. async function submitBabelInstance(e) {
  18497. e.preventDefault();
  18498. const id = document.getElementById('modal-babel-instance-id').value;
  18499. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18500. const payload = {
  18501. id: id || undefined,
  18502. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18503. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18504. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18505. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18506. enabled: isEnabled,
  18507. disabled: !isEnabled,
  18508. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18509. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18510. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18511. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18512. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18513. };
  18514. try {
  18515. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18516. method: 'POST',
  18517. headers: { 'Content-Type': 'application/json' },
  18518. body: JSON.stringify(payload)
  18519. });
  18520. if (!res.ok) throw new Error(await res.text());
  18521. closeBabelInstanceModal();
  18522. showToast('Saved', `Babel instance saved`, 'success');
  18523. await loadDynamicRouting(false);
  18524. } catch (err) {
  18525. showToast('Error', err.message, 'error');
  18526. }
  18527. }
  18528. async function enableSelectedBabelInstance() {
  18529. const id = state.selectedBabelRow?.instances;
  18530. if (!id) return;
  18531. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18532. await loadDynamicRouting(false);
  18533. }
  18534. async function disableSelectedBabelInstance() {
  18535. const id = state.selectedBabelRow?.instances;
  18536. if (!id) return;
  18537. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18538. await loadDynamicRouting(false);
  18539. }
  18540. async function removeSelectedBabelInstance() {
  18541. const id = state.selectedBabelRow?.instances;
  18542. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18543. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18544. state.selectedBabelRow.instances = null;
  18545. await loadDynamicRouting(false);
  18546. }
  18547. function toggleBabelAuthKey() {
  18548. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18549. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18550. if (wrap) {
  18551. if (authVal === 'mac') wrap.classList.remove('hidden');
  18552. else wrap.classList.add('hidden');
  18553. }
  18554. }
  18555. function openBabelInterfaceModal() {
  18556. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18557. document.getElementById('modal-babel-iface-id').value = '';
  18558. const instSel = document.getElementById('modal-babel-iface-instance');
  18559. if (instSel) {
  18560. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18561. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18562. if (state.babelInstances && state.babelInstances.length > 0) {
  18563. instSel.value = state.babelInstances[0].name;
  18564. }
  18565. }
  18566. const dl = document.getElementById('babel-iface-datalist');
  18567. if (dl) {
  18568. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18569. }
  18570. document.getElementById('modal-babel-iface-pattern').value = '*';
  18571. document.getElementById('modal-babel-iface-type').value = 'wired';
  18572. document.getElementById('modal-babel-iface-auth').value = 'none';
  18573. document.getElementById('modal-babel-iface-auth-key').value = '';
  18574. toggleBabelAuthKey();
  18575. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18576. document.getElementById('modal-babel-iface-hello').value = '4';
  18577. document.getElementById('modal-babel-iface-update').value = '16';
  18578. document.getElementById('modal-babel-iface-comment').value = '';
  18579. document.getElementById('modal-babel-iface-enabled').checked = true;
  18580. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18581. }
  18582. function openEditBabelInterfaceModal(id) {
  18583. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18584. if (!iface) return;
  18585. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18586. document.getElementById('modal-babel-iface-id').value = iface.id;
  18587. const instSel = document.getElementById('modal-babel-iface-instance');
  18588. if (instSel) {
  18589. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18590. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18591. instSel.value = iface.instance || 'all';
  18592. }
  18593. const dl = document.getElementById('babel-iface-datalist');
  18594. if (dl) {
  18595. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18596. }
  18597. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18598. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18599. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18600. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18601. toggleBabelAuthKey();
  18602. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18603. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18604. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18605. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18606. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18607. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18608. }
  18609. function closeBabelInterfaceModal() {
  18610. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18611. }
  18612. async function submitBabelInterface(e) {
  18613. e.preventDefault();
  18614. const id = document.getElementById('modal-babel-iface-id').value;
  18615. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18616. const payload = {
  18617. id: id || undefined,
  18618. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18619. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18620. type: document.getElementById('modal-babel-iface-type').value,
  18621. auth: document.getElementById('modal-babel-iface-auth').value,
  18622. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18623. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18624. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18625. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18626. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18627. disabled: !isEnabled
  18628. };
  18629. try {
  18630. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18631. method: 'POST',
  18632. headers: { 'Content-Type': 'application/json' },
  18633. body: JSON.stringify(payload)
  18634. });
  18635. if (!res.ok) throw new Error(await res.text());
  18636. closeBabelInterfaceModal();
  18637. showToast('Saved', `Babel interface template saved`, 'success');
  18638. await loadDynamicRouting(false);
  18639. } catch (err) {
  18640. showToast('Error', err.message, 'error');
  18641. }
  18642. }
  18643. async function enableSelectedBabelInterface() {
  18644. const id = state.selectedBabelRow?.interfaces;
  18645. if (!id) return;
  18646. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18647. await loadDynamicRouting(false);
  18648. }
  18649. async function disableSelectedBabelInterface() {
  18650. const id = state.selectedBabelRow?.interfaces;
  18651. if (!id) return;
  18652. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18653. await loadDynamicRouting(false);
  18654. }
  18655. async function removeSelectedBabelInterface() {
  18656. const id = state.selectedBabelRow?.interfaces;
  18657. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18658. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18659. state.selectedBabelRow.interfaces = null;
  18660. await loadDynamicRouting(false);
  18661. }
  18662. // ==============================================================================
  18663. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18664. // ==============================================================================
  18665. state.radvInstances = [];
  18666. state.radvInterfaces = [];
  18667. state.selectedRadvRow = {};
  18668. state.activeRadvTab = 'instances';
  18669. function switchRadvTab(tab) {
  18670. state.activeRadvTab = tab;
  18671. ['instances', 'interfaces'].forEach(t => {
  18672. const pane = document.getElementById(`radv-pane-${t}`);
  18673. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18674. if (pane) {
  18675. if (t === tab) pane.classList.remove('hidden');
  18676. else pane.classList.add('hidden');
  18677. }
  18678. if (btn) {
  18679. if (t === tab) {
  18680. 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';
  18681. } else {
  18682. 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';
  18683. }
  18684. }
  18685. });
  18686. }
  18687. function selectRadvRow(tab, id) {
  18688. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18689. state.selectedRadvRow[tab] = id;
  18690. if (tab === 'instances') {
  18691. renderRAdvInstances();
  18692. const btnEn = document.getElementById('btn-radv-inst-enable');
  18693. const btnDis = document.getElementById('btn-radv-inst-disable');
  18694. const btnRem = document.getElementById('btn-radv-inst-remove');
  18695. if (btnEn) btnEn.disabled = false;
  18696. if (btnDis) btnDis.disabled = false;
  18697. if (btnRem) btnRem.disabled = false;
  18698. } else if (tab === 'interfaces') {
  18699. renderRAdvInterfaces();
  18700. const btnEn = document.getElementById('btn-radv-iface-enable');
  18701. const btnDis = document.getElementById('btn-radv-iface-disable');
  18702. const btnRem = document.getElementById('btn-radv-iface-remove');
  18703. if (btnEn) btnEn.disabled = false;
  18704. if (btnDis) btnDis.disabled = false;
  18705. if (btnRem) btnRem.disabled = false;
  18706. }
  18707. }
  18708. function renderRAdvInstances() {
  18709. const tbody = document.getElementById('radv-instances-table-body');
  18710. if (!tbody) return;
  18711. const countEl = document.getElementById('radv-instances-footer-count');
  18712. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18713. let list = state.radvInstances || [];
  18714. if (filter) {
  18715. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18716. }
  18717. if (countEl) countEl.innerText = list.length;
  18718. const selId = state.selectedRadvRow?.instances;
  18719. tbody.innerHTML = list.map((inst, idx) => {
  18720. const isSel = inst.id === selId;
  18721. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18722. const flagD = inst.disabled
  18723. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  18724. : (inst.running
  18725. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  18726. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  18727. return `
  18728. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18729. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18730. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18731. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18732. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18733. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18734. </td>
  18735. <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>
  18736. </tr>
  18737. `;
  18738. }).join('');
  18739. }
  18740. function renderRAdvInterfaces() {
  18741. const tbody = document.getElementById('radv-interfaces-table-body');
  18742. if (!tbody) return;
  18743. const countEl = document.getElementById('radv-interfaces-footer-count');
  18744. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18745. let list = state.radvInterfaces || [];
  18746. if (filter) {
  18747. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18748. }
  18749. if (countEl) countEl.innerText = list.length;
  18750. const selId = state.selectedRadvRow?.interfaces;
  18751. tbody.innerHTML = list.map((iface, idx) => {
  18752. const isSel = iface.id === selId;
  18753. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18754. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18755. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18756. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18757. return `
  18758. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18759. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18760. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18761. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18762. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18763. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18764. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18765. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18766. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18767. </tr>
  18768. `;
  18769. }).join('');
  18770. }
  18771. function openRAdvInstanceModal() {
  18772. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18773. document.getElementById('modal-radv-instance-id').value = '';
  18774. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18775. document.getElementById('modal-radv-instance-comment').value = '';
  18776. document.getElementById('modal-radv-instance-enabled').checked = true;
  18777. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18778. }
  18779. function openEditRAdvInstanceModal(id) {
  18780. const inst = (state.radvInstances || []).find(i => i.id === id);
  18781. if (!inst) return;
  18782. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18783. document.getElementById('modal-radv-instance-id').value = inst.id;
  18784. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18785. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18786. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18787. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18788. }
  18789. function closeRAdvInstanceModal() {
  18790. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18791. }
  18792. async function submitRAdvInstance(e) {
  18793. e.preventDefault();
  18794. const id = document.getElementById('modal-radv-instance-id').value;
  18795. const payload = {
  18796. id: id || undefined,
  18797. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18798. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18799. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18800. };
  18801. try {
  18802. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18803. method: 'POST',
  18804. headers: { 'Content-Type': 'application/json' },
  18805. body: JSON.stringify(payload)
  18806. });
  18807. if (!res.ok) throw new Error(await res.text());
  18808. closeRAdvInstanceModal();
  18809. showToast('Saved', `RAdv instance saved`, 'success');
  18810. await loadDynamicRouting(false);
  18811. } catch (err) {
  18812. showToast('Error', err.message, 'error');
  18813. }
  18814. }
  18815. async function enableSelectedRadvInstance() {
  18816. const id = state.selectedRadvRow?.instances;
  18817. if (!id) return;
  18818. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18819. await loadDynamicRouting(false);
  18820. }
  18821. async function disableSelectedRadvInstance() {
  18822. const id = state.selectedRadvRow?.instances;
  18823. if (!id) return;
  18824. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18825. await loadDynamicRouting(false);
  18826. }
  18827. async function removeSelectedRadvInstance() {
  18828. const id = state.selectedRadvRow?.instances;
  18829. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18830. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18831. state.selectedRadvRow.instances = null;
  18832. await loadDynamicRouting(false);
  18833. }
  18834. function openRAdvInterfaceModal() {
  18835. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18836. document.getElementById('modal-radv-iface-id').value = '';
  18837. const dl = document.getElementById('radv-iface-datalist');
  18838. if (dl) {
  18839. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18840. }
  18841. const instSel = document.getElementById('modal-radv-iface-instance');
  18842. if (instSel && instSel.tagName === 'SELECT') {
  18843. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18844. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18845. instSel.value = (state.radvInstances && state.radvInstances.length > 0) ? state.radvInstances[0].name : 'default';
  18846. } else if (instSel) {
  18847. instSel.value = 'default';
  18848. }
  18849. document.getElementById('modal-radv-iface-interface').value = '*';
  18850. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18851. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18852. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18853. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18854. document.getElementById('modal-radv-iface-prefixes').value = '';
  18855. document.getElementById('modal-radv-iface-rdnss').value = '';
  18856. document.getElementById('modal-radv-iface-comment').value = '';
  18857. document.getElementById('modal-radv-iface-enabled').checked = true;
  18858. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18859. }
  18860. function openEditRAdvInterfaceModal(id) {
  18861. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18862. if (!iface) return;
  18863. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18864. document.getElementById('modal-radv-iface-id').value = iface.id;
  18865. const dl = document.getElementById('radv-iface-datalist');
  18866. if (dl) {
  18867. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18868. }
  18869. const instSel = document.getElementById('modal-radv-iface-instance');
  18870. if (instSel && instSel.tagName === 'SELECT') {
  18871. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18872. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18873. instSel.value = iface.instance || 'default';
  18874. } else if (instSel) {
  18875. instSel.value = iface.instance || '';
  18876. }
  18877. document.getElementById('modal-radv-iface-interface').value = iface.interface || '*';
  18878. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18879. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18880. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18881. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18882. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18883. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18884. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18885. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18886. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18887. }
  18888. function closeRAdvInterfaceModal() {
  18889. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18890. }
  18891. async function submitRAdvInterface(e) {
  18892. e.preventDefault();
  18893. const id = document.getElementById('modal-radv-iface-id').value;
  18894. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18895. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18896. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18897. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18898. const payload = {
  18899. id: id || undefined,
  18900. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18901. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18902. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18903. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18904. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18905. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18906. prefixes: prefixes,
  18907. rdnss: rdnss,
  18908. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18909. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18910. };
  18911. try {
  18912. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18913. method: 'POST',
  18914. headers: { 'Content-Type': 'application/json' },
  18915. body: JSON.stringify(payload)
  18916. });
  18917. if (!res.ok) throw new Error(await res.text());
  18918. closeRAdvInterfaceModal();
  18919. showToast('Saved', `RAdv interface saved`, 'success');
  18920. await loadDynamicRouting(false);
  18921. } catch (err) {
  18922. showToast('Error', err.message, 'error');
  18923. }
  18924. }
  18925. async function enableSelectedRadvInterface() {
  18926. const id = state.selectedRadvRow?.interfaces;
  18927. if (!id) return;
  18928. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18929. await loadDynamicRouting(false);
  18930. }
  18931. async function disableSelectedRadvInterface() {
  18932. const id = state.selectedRadvRow?.interfaces;
  18933. if (!id) return;
  18934. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18935. await loadDynamicRouting(false);
  18936. }
  18937. async function removeSelectedRadvInterface() {
  18938. const id = state.selectedRadvRow?.interfaces;
  18939. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  18940. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  18941. state.selectedRadvRow.interfaces = null;
  18942. await loadDynamicRouting(false);
  18943. }