app.js 894 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. vxlanTunnels: [],
  109. vxlanVteps: [],
  110. pppSecrets: [],
  111. pppProfiles: [],
  112. pppActiveSessions: [],
  113. pppoeServer: null,
  114. pptpServer: null,
  115. l2tpServer: null,
  116. ipsecServer: null,
  117. ifaceFilter: 'all',
  118. currentModalIface: null,
  119. isPolling: false,
  120. expandedParents: new Set(['eth0']),
  121. pppoeData: null,
  122. wgData: null,
  123. ipsecData: null,
  124. l2tpData: null,
  125. pptpData: null,
  126. fwSummary: null,
  127. filterRules: [],
  128. natRules: [],
  129. mangleRules: [],
  130. addressLists: [],
  131. connections: [],
  132. policyRules: [],
  133. routingTables: [],
  134. routingFilters: [],
  135. filterChainSelected: 'all',
  136. activeToolsSubTab: 'ping',
  137. dhcpClients: [],
  138. dhcpSummary: null,
  139. dhcpServerTab: 'servers',
  140. dhcpServers: [],
  141. dhcpNetworks: [],
  142. dhcpLeases: [],
  143. dhcpOptions: [],
  144. dhcpServerSummary: null,
  145. sdwanGroups: [],
  146. sdwanTelemetry: null
  147. };
  148. const API_BASE = '/api';
  149. function escapeHtml(str) {
  150. if (str === null || str === undefined) return '';
  151. return String(str)
  152. .replace(/&/g, '&')
  153. .replace(/</g, '&lt;')
  154. .replace(/>/g, '&gt;')
  155. .replace(/"/g, '&quot;')
  156. .replace(/'/g, '&#039;');
  157. }
  158. function formatBytes(bytes) {
  159. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  160. const k = 1024;
  161. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  162. const i = Math.floor(Math.log(bytes) / Math.log(k));
  163. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  164. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  165. }
  166. // Initialize on page load
  167. document.addEventListener('DOMContentLoaded', async () => {
  168. initTableSorting();
  169. // Verify authentication before bootstrapping telemetry and views
  170. const isAuthenticated = await checkAuthStatus();
  171. if (isAuthenticated) {
  172. const hash = window.location.hash.replace('#', '') || 'dashboard';
  173. navigate(hash);
  174. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  175. if (!window._telemetryInterval) {
  176. window._telemetryInterval = setInterval(() => {
  177. if (state.isPolling && state.currentUser && !document.hidden) {
  178. fetchData(false);
  179. }
  180. }, 5000);
  181. }
  182. }
  183. });
  184. let trafficEventSource = null;
  185. let trafficPollFallback = null;
  186. function initLiveTrafficStream() {
  187. if (trafficEventSource) {
  188. try { trafficEventSource.close(); } catch(e) {}
  189. trafficEventSource = null;
  190. }
  191. if (trafficPollFallback) {
  192. clearInterval(trafficPollFallback);
  193. trafficPollFallback = null;
  194. }
  195. if (window.EventSource) {
  196. try {
  197. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  198. trafficEventSource.onmessage = (event) => {
  199. try {
  200. const data = JSON.parse(event.data);
  201. updateLiveInterfaceTraffic(data);
  202. } catch (e) {
  203. console.error('Error parsing live traffic event:', e);
  204. }
  205. };
  206. trafficEventSource.onerror = () => {
  207. // Fallback polling if SSE disconnects
  208. if (!trafficPollFallback) {
  209. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  210. }
  211. };
  212. trafficEventSource.onopen = () => {
  213. if (trafficPollFallback) {
  214. clearInterval(trafficPollFallback);
  215. trafficPollFallback = null;
  216. }
  217. };
  218. return;
  219. } catch (e) {
  220. console.warn('EventSource failed, using 1s polling fallback:', e);
  221. }
  222. }
  223. // Fallback if EventSource is unavailable
  224. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  225. }
  226. async function pollLiveTrafficSnapshot() {
  227. try {
  228. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  229. if (res.ok) {
  230. const data = await res.json();
  231. updateLiveInterfaceTraffic(data);
  232. }
  233. } catch (e) {}
  234. }
  235. function updateLiveInterfaceTraffic(data) {
  236. if (!data || !data.interfaces) return;
  237. state.latestTraffic = data;
  238. // 1. Update Top & Dashboard Total Bandwidth Indicators
  239. const rxHuman = data.total_rx_human || '0 B/s';
  240. const txHuman = data.total_tx_human || '0 B/s';
  241. const statRx = document.getElementById('stat-traffic-rx');
  242. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  243. const statTx = document.getElementById('stat-traffic-tx');
  244. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  245. // 2. Update state.interfaces rates in-memory
  246. if (Array.isArray(state.interfaces)) {
  247. state.interfaces.forEach(i => {
  248. const live = data.interfaces[i.name];
  249. if (live) {
  250. i.rate = {
  251. rx_bytes_sec: live.rx_bytes_sec,
  252. tx_bytes_sec: live.tx_bytes_sec,
  253. rx_human: live.rx_human,
  254. tx_human: live.tx_human
  255. };
  256. i.stats = {
  257. rx_bytes: live.rx_bytes,
  258. tx_bytes: live.tx_bytes,
  259. rx_packets: live.rx_packets,
  260. tx_packets: live.tx_packets,
  261. rx_errors: live.rx_errors,
  262. tx_errors: live.tx_errors,
  263. rx_dropped: live.rx_dropped,
  264. tx_dropped: live.tx_dropped
  265. };
  266. }
  267. });
  268. }
  269. // 3. Update all live UI rate spans in-place (ZERO flicker)
  270. Object.keys(data.interfaces).forEach(name => {
  271. const live = data.interfaces[name];
  272. // Dashboard Port Matrix Card
  273. const cardRate = document.getElementById(`port-card-rate-${name}`);
  274. if (cardRate && cardRate.innerText !== live.rx_human) {
  275. cardRate.innerText = live.rx_human;
  276. }
  277. // Dashboard Quick Interfaces Table
  278. const quickRx = document.getElementById(`quick-rx-${name}`);
  279. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  280. const quickTx = document.getElementById(`quick-tx-${name}`);
  281. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  282. // Main Interfaces Tree Table
  283. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  284. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  285. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  286. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  287. // VLAN Sub-interfaces Table
  288. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  289. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  290. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  291. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  292. // VLAN Page Table
  293. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  294. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  295. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  296. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  297. });
  298. }
  299. // Navigation Handler
  300. function navigate(tabName) {
  301. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  302. navigate('bgp');
  303. return;
  304. }
  305. if (tabName === 'vlans') {
  306. navigate('interfaces');
  307. return;
  308. }
  309. if (tabName === 'persistence') {
  310. navigate('dashboard');
  311. return;
  312. }
  313. stopFwStatPolling();
  314. stopNATStatPolling();
  315. stopMangleStatPolling();
  316. state.activeTab = tabName;
  317. window.location.hash = tabName;
  318. // Update nav links styling
  319. document.querySelectorAll('.nav-link').forEach(link => {
  320. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  321. });
  322. const activeNav = document.getElementById(`nav-${tabName}`);
  323. if (activeNav) {
  324. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  325. }
  326. // Update page headers
  327. const titles = {
  328. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  329. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  330. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  331. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  332. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  333. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  334. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  335. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  336. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  337. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  338. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  339. rip: { title: 'RIP Dynamic Routing', sub: 'Routing Information Protocol (RIPv2 IPv4 & RIPng IPv6) hop-count distance-vector routing' },
  340. bfd: { title: 'BFD Fast Session Detection', sub: 'Bidirectional Forwarding Detection (BFD) sub-second link failure detection for BGP and OSPF' },
  341. babel: { title: 'Babel Dynamic Routing', sub: 'Babel loop-avoiding distance-vector routing for wired and wireless mesh networks (RFC 8966)' },
  342. radv: { title: 'IPv6 Router Advertisements (RAdv)', sub: 'BIRD 2 ICMPv6 Router Advertisement daemon for IPv6 SLAAC autoconfiguration and RDNSS' },
  343. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  344. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  345. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  346. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  347. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  348. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  349. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  350. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  351. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  352. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  353. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  354. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  355. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  356. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  357. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  358. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  359. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  360. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  361. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  362. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  363. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  364. };
  365. const header = titles[tabName] || titles.dashboard;
  366. const pTitle = document.getElementById('page-title');
  367. if (pTitle) pTitle.innerText = header.title;
  368. const pSub = document.getElementById('page-subtitle');
  369. if (pSub) pSub.innerText = header.sub;
  370. // Toggle sections dynamically for all section elements
  371. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  372. if (el.id === `section-${tabName}`) {
  373. el.classList.remove('hidden');
  374. } else {
  375. el.classList.add('hidden');
  376. }
  377. });
  378. if (tabName === 'interfaces') {
  379. loadRoles();
  380. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  381. else switchIfaceSubTab('tree');
  382. }
  383. if (tabName === 'bridge') loadBridge();
  384. if (tabName === 'firewall') loadFirewall();
  385. if (tabName === 'routes') loadRoutes();
  386. if (tabName === 'sdwan') loadSDWAN();
  387. if (tabName === 'bgp') {
  388. loadDynamicRouting();
  389. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  390. }
  391. if (tabName === 'ospf') {
  392. loadDynamicRouting();
  393. switchOspfTab(state.activeOspfTab || 'instances');
  394. }
  395. if (tabName === 'rip') {
  396. loadDynamicRouting();
  397. switchRipTab(state.activeRipTab || 'instances');
  398. }
  399. if (tabName === 'bfd') {
  400. loadDynamicRouting();
  401. switchBfdTab(state.activeBfdTab || 'config');
  402. }
  403. if (tabName === 'babel') {
  404. loadDynamicRouting();
  405. switchBabelTab(state.activeBabelTab || 'instances');
  406. }
  407. if (tabName === 'radv') {
  408. loadDynamicRouting();
  409. switchRadvTab(state.activeRadvTab || 'instances');
  410. }
  411. if (tabName === 'routing-filters') loadDynamicRouting();
  412. if (tabName === 'dynamic-routing') loadDynamicRouting();
  413. if (tabName === 'ppp') loadPPP();
  414. if (tabName === 'eoip') loadEoIP();
  415. if (tabName === 'vxlan') loadVXLAN();
  416. if (tabName === 'aerotun') loadAeroTUN();
  417. if (tabName === 'pppoe') loadPPPoE();
  418. if (tabName === 'wireguard') loadWireGuard();
  419. if (tabName === 'ipsec') loadIPSec();
  420. if (tabName === 'l2tp') loadL2TP();
  421. if (tabName === 'pptp') loadPPTP();
  422. if (tabName === 'tools') loadToolsView();
  423. if (tabName === 'dhcp-client') loadDHCPClients();
  424. if (tabName === 'dhcp-server') loadDHCPServer();
  425. if (tabName === 'vrrp') loadVRRP();
  426. if (tabName === 'bwtest') loadBwTestView();
  427. if (tabName === 'settings') loadSettingsData();
  428. if (tabName === 'users') loadUsers();
  429. if (tabName === 'certificates') loadCertificates();
  430. if (tabName === 'reverse_proxy') loadReverseProxy();
  431. if (tabName === 'services') loadServices();
  432. if (tabName === 'updates') loadUpdateStatus();
  433. if (tabName === 'logs') loadLogs();
  434. setTimeout(initTableSorting, 50);
  435. }
  436. // Fetch all core system, network and VPN telemetry
  437. function fetchData(isManual = false) {
  438. if (coreRefreshPromise) return coreRefreshPromise;
  439. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  440. return coreRefreshPromise;
  441. }
  442. async function refreshCoreData(isManual = false) {
  443. const spinner = document.getElementById('refresh-spinner');
  444. if (isManual && spinner) spinner.classList.add('animate-spin');
  445. try {
  446. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  447. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  448. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  449. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  450. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  451. summaryFetch('/vlans'),
  452. summaryFetch('/vpn/status'),
  453. summaryFetch('/firewall/summary'),
  454. summaryFetch('/routing/dynamic/summary'),
  455. summaryFetch('/bridge/summary'),
  456. summaryFetch('/dhcp/clients/summary'),
  457. summaryFetch('/dhcp/clients'),
  458. summaryFetch('/vrrp/summary').catch(() => null),
  459. summaryFetch('/roles').catch(() => null)
  460. ]);
  461. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  462. if (rolesRes && rolesRes.ok) {
  463. state.roles = await rolesRes.json();
  464. const countEl = document.getElementById('badge-roles-count');
  465. if (countEl) countEl.innerText = (state.roles || []).length;
  466. }
  467. if (vrrpSumRes && vrrpSumRes.ok) {
  468. state.vrrpSummary = await vrrpSumRes.json();
  469. renderVRRPSummary();
  470. }
  471. if (dhcpSumRes && dhcpSumRes.ok) {
  472. state.dhcpSummary = await dhcpSumRes.json();
  473. const bDhcp = document.getElementById('badge-dhcp-client-count');
  474. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  475. }
  476. if (dhcpClientsRes && dhcpClientsRes.ok) {
  477. state.dhcpClients = await dhcpClientsRes.json();
  478. }
  479. if (brSummaryRes.ok) {
  480. state.bridgeSummary = await brSummaryRes.json();
  481. const bBridge = document.getElementById('badge-bridge-count');
  482. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  483. const sBr = document.getElementById('bridge-stat-bridges');
  484. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  485. const sPorts = document.getElementById('bridge-stat-ports');
  486. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  487. const sHosts = document.getElementById('bridge-stat-hosts');
  488. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  489. }
  490. if (statusRes.ok) state.systemStatus = await statusRes.json();
  491. if (ifacesRes.ok) {
  492. const ifacesData = await ifacesRes.json();
  493. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  494. state.interfaces = rawIfaces.filter(i => {
  495. if (!i.name) return false;
  496. if (i.name.startsWith('ep_')) return false;
  497. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  498. });
  499. try { populateToolsInterfaces(); } catch (e) {}
  500. }
  501. if (vlansRes.ok) {
  502. const vlansData = await vlansRes.json();
  503. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  504. }
  505. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  506. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  507. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  508. updateSystemMetrics();
  509. updateBadges();
  510. if (state.activeTab === 'dashboard') renderDashboard();
  511. if (state.activeTab === 'interfaces') {
  512. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  513. else renderInterfacesList();
  514. }
  515. if (state.activeTab === 'vlans') renderVlansList();
  516. if (state.activeTab === 'firewall') await loadFirewall(false);
  517. if (state.activeTab === 'routes') await loadRoutes(false);
  518. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf' || state.activeTab === 'rip' || state.activeTab === 'bfd' || state.activeTab === 'babel' || state.activeTab === 'radv') await loadDynamicRouting(false);
  519. if (state.activeTab === 'ppp') await loadPPP(false);
  520. if (state.activeTab === 'eoip') await loadEoIP(false);
  521. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  522. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  523. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  524. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  525. if (state.activeTab === 'ipsec') await loadIPSec(false);
  526. if (state.activeTab === 'l2tp') await loadL2TP(false);
  527. if (state.activeTab === 'pptp') await loadPPTP(false);
  528. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  529. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  530. if (state.activeTab === 'vrrp') await loadVRRP(false);
  531. if (state.activeTab === 'settings') await loadSettingsData(false);
  532. if (state.activeTab === 'users') await loadUsers(false);
  533. if (state.activeTab === 'certificates') await loadCertificates(false);
  534. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  535. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  536. if (state.activeTab === 'services') await loadServices(false);
  537. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  538. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  539. } catch (err) {
  540. console.error('Failed to fetch router state:', err);
  541. } finally {
  542. if (isManual && spinner) {
  543. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  544. }
  545. }
  546. }
  547. // Update Top KPI and Sidebar Telemetry
  548. function updateSystemMetrics() {
  549. const s = state.systemStatus;
  550. const v = state.vpnStatus;
  551. if (!s) return;
  552. // Sidebar Host & Uptime
  553. const sideHost = document.getElementById('side-hostname');
  554. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  555. const sideUp = document.getElementById('side-uptime');
  556. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  557. const sideGw = document.getElementById('side-gateway-ip');
  558. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  559. // Compute CPU Metrics
  560. let cpuPct = 0;
  561. if (s.cpu_pct !== undefined) {
  562. cpuPct = s.cpu_pct;
  563. } else if (s.cpu_load && s.cpu_load.length > 0) {
  564. const cores = s.cpu_cores || 1;
  565. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  566. }
  567. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  568. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  569. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  570. // Sidebar CPU
  571. const sideCpuVal = document.getElementById('side-cpu-val');
  572. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  573. const sideCpuBar = document.getElementById('side-cpu-bar');
  574. if (sideCpuBar) {
  575. sideCpuBar.style.width = cpuWidth;
  576. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  577. }
  578. // Dashboard CPU Card
  579. const dashCpuVal = document.getElementById('dash-cpu-val');
  580. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  581. const dashCpuBar = document.getElementById('dash-cpu-bar');
  582. if (dashCpuBar) {
  583. dashCpuBar.style.width = cpuWidth;
  584. if (cpuPct > 85) {
  585. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  586. } else if (cpuPct > 65) {
  587. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  588. } else {
  589. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  590. }
  591. }
  592. const dashCpuCores = document.getElementById('dash-cpu-cores');
  593. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  594. const dashCpuLoad = document.getElementById('dash-cpu-load');
  595. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  596. const dashCpuStatus = document.getElementById('dash-cpu-status');
  597. if (dashCpuStatus) {
  598. if (cpuPct > 85) {
  599. dashCpuStatus.innerText = 'High';
  600. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  601. } else if (cpuPct > 65) {
  602. dashCpuStatus.innerText = 'Heavy';
  603. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  604. } else {
  605. dashCpuStatus.innerText = 'Normal';
  606. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  607. }
  608. }
  609. // Compute RAM Metrics
  610. const memPct = Math.round(s.mem_usage_pct || 0);
  611. const memPctStr = `${memPct}%`;
  612. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  613. const usedMB = s.mem_used_mb || 0;
  614. const totalMB = s.mem_total_mb || 0;
  615. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  616. function fmtMemMB(mb) {
  617. if (mb >= 1024) {
  618. return `${(mb / 1024).toFixed(1)} GB`;
  619. }
  620. return `${mb} MB`;
  621. }
  622. // Sidebar RAM
  623. const sideRamVal = document.getElementById('side-ram-val');
  624. if (sideRamVal) sideRamVal.innerText = memPctStr;
  625. const sideRamBar = document.getElementById('side-ram-bar');
  626. if (sideRamBar) sideRamBar.style.width = memWidth;
  627. // Dashboard RAM Card
  628. const dashRamVal = document.getElementById('dash-ram-val');
  629. if (dashRamVal) dashRamVal.innerText = memPctStr;
  630. const dashRamBar = document.getElementById('dash-ram-bar');
  631. if (dashRamBar) {
  632. dashRamBar.style.width = memWidth;
  633. if (memPct > 85) {
  634. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  635. } else if (memPct > 70) {
  636. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  637. } else {
  638. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  639. }
  640. }
  641. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  642. if (dashRamUsedTotal) {
  643. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  644. }
  645. const dashRamFree = document.getElementById('dash-ram-free');
  646. if (dashRamFree) {
  647. dashRamFree.innerText = fmtMemMB(freeMB);
  648. }
  649. const dashRamStatus = document.getElementById('dash-ram-status');
  650. if (dashRamStatus) {
  651. if (memPct > 85) {
  652. dashRamStatus.innerText = 'High';
  653. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  654. } else {
  655. dashRamStatus.innerText = 'Active';
  656. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  657. }
  658. }
  659. // Legacy Dashboard Stats (Safe checks)
  660. const elIfacesUp = document.getElementById('stat-ifaces-up');
  661. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  662. const elIfacesTot = document.getElementById('stat-ifaces-total');
  663. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  664. const elIfacesDown = document.getElementById('stat-ifaces-down');
  665. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  666. const elVlans = document.getElementById('stat-vlans-count');
  667. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  668. // VPN Status Indicators
  669. if (v) {
  670. const totalActive = v.total_active_tunnels || 0;
  671. const statVpnActive = document.getElementById('stat-vpn-active');
  672. if (statVpnActive) statVpnActive.innerText = totalActive;
  673. const tunnelsDot = document.getElementById('tunnels-dot');
  674. const tunnelsLabel = document.getElementById('tunnels-label');
  675. if (tunnelsDot && tunnelsLabel) {
  676. if (totalActive > 0) {
  677. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  678. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  679. } else {
  680. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  681. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  682. }
  683. }
  684. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  685. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  686. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  687. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  688. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  689. }
  690. // Total Live Bandwidth Rate
  691. let totalRx = 0;
  692. let totalTx = 0;
  693. (state.interfaces || []).forEach(i => {
  694. if (i.rate) {
  695. totalRx += i.rate.rx_bytes_sec || 0;
  696. totalTx += i.rate.tx_bytes_sec || 0;
  697. }
  698. });
  699. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  700. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  701. }
  702. function setDotBadge(id, active) {
  703. const el = document.getElementById(id);
  704. if (!el) return;
  705. if (active) {
  706. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  707. } else {
  708. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  709. }
  710. }
  711. function updateBadges() {
  712. const bIfaces = document.getElementById('badge-ifaces-count');
  713. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  714. const bVlans = document.getElementById('badge-vlans-count');
  715. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  716. if (state.fwSummary) {
  717. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  718. const badgeFw = document.getElementById('badge-firewall-count');
  719. if (badgeFw) badgeFw.innerText = totalFwRules;
  720. }
  721. if (state.vpnStatus) {
  722. const v = state.vpnStatus;
  723. const bEoIP = document.getElementById('badge-eoip-count');
  724. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  725. const bVXLAN = document.getElementById('badge-vxlan-count');
  726. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  727. const bAero = document.getElementById('badge-aerotun-count');
  728. if (bAero) bAero.innerText = v.total_aerotun || 0;
  729. const bPPPSess = document.getElementById('badge-ppp-sessions');
  730. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  731. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  732. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  733. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  734. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  735. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  736. }
  737. if (state.dynSummary) {
  738. const d = state.dynSummary;
  739. setDotBadge('badge-bgp-dot', d.bgp_running);
  740. setDotBadge('badge-ospf-dot', d.ospf_running);
  741. setDotBadge('badge-rip-dot', d.rip_running);
  742. setDotBadge('badge-bfd-dot', d.bfd_running);
  743. setDotBadge('badge-babel-dot', d.babel_running);
  744. setDotBadge('badge-radv-dot', d.radv_running);
  745. const bBgp = document.getElementById('badge-bgp-count');
  746. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  747. const bOspf = document.getElementById('badge-ospf-count');
  748. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  749. const bRip = document.getElementById('badge-rip-count');
  750. if (bRip) bRip.innerText = (state.ripInterfaces || []).length;
  751. const bBfd = document.getElementById('badge-bfd-count');
  752. if (bBfd) bBfd.innerText = (state.bfdInterfaces || []).length;
  753. const bBabel = document.getElementById('badge-babel-count');
  754. if (bBabel) bBabel.innerText = (state.babelInterfaces || []).length;
  755. const bRadv = document.getElementById('badge-radv-count');
  756. if (bRadv) bRadv.innerText = (state.radvInterfaces || []).length;
  757. const bFilters = document.getElementById('badge-filters-count');
  758. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  759. }
  760. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  761. if (bDhcpServer) {
  762. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  763. }
  764. }
  765. // Render Dashboard View
  766. function renderDashboard() {
  767. const matrix = document.getElementById('port-matrix');
  768. if (!matrix) return;
  769. const ifaces = state.interfaces || [];
  770. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  771. if (matrix.dataset.sig === sig) {
  772. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  773. }
  774. matrix.dataset.sig = sig;
  775. matrix.innerHTML = '';
  776. (state.interfaces || []).forEach(iface => {
  777. const isUp = iface.state === 'UP';
  778. const isVlan = iface.is_vlan;
  779. const portCard = document.createElement('div');
  780. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  781. isUp
  782. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  783. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  784. }`;
  785. portCard.onclick = () => openIfaceModal(iface.name);
  786. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  787. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  788. portCard.innerHTML = `
  789. <div class="flex items-center justify-between mb-2">
  790. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  791. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  792. </div>
  793. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  794. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  795. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  796. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  797. </div>
  798. `;
  799. matrix.appendChild(portCard);
  800. });
  801. const ifaceTbody = document.getElementById('quick-interfaces-table');
  802. if (ifaceTbody) {
  803. ifaceTbody.innerHTML = '';
  804. (state.interfaces || []).forEach(i => {
  805. const isUp = i.state === 'UP';
  806. const tr = document.createElement('tr');
  807. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  808. tr.onclick = () => openIfaceModal(i.name);
  809. const rxStr = i.rate?.rx_human || '0 B/s';
  810. const txStr = i.rate?.tx_human || '0 B/s';
  811. tr.innerHTML = `
  812. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  813. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  814. <span>${i.name}</span>
  815. </td>
  816. <td class="py-2.5 text-slate-300 font-sans">
  817. ${getRoleBadge(i.role || 'LAN')}
  818. </td>
  819. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  820. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  821. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  822. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  823. </td>
  824. <td class="py-2.5 text-right font-sans font-semibold">
  825. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  826. </td>
  827. `;
  828. ifaceTbody.appendChild(tr);
  829. });
  830. }
  831. const vlanTbody = document.getElementById('quick-vlans-table');
  832. if (vlanTbody) {
  833. vlanTbody.innerHTML = '';
  834. }
  835. }
  836. // Expand / Collapse Handlers
  837. function toggleExpand(parentName) {
  838. if (state.expandedParents.has(parentName)) {
  839. state.expandedParents.delete(parentName);
  840. } else {
  841. state.expandedParents.add(parentName);
  842. }
  843. renderInterfacesList();
  844. }
  845. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  846. function supportsVLAN(iface) {
  847. if (!iface) return false;
  848. if (iface.is_vlan) return false;
  849. const name = (iface.name || '').toLowerCase();
  850. const type = (iface.type || '').toLowerCase();
  851. const role = (iface.role || '').toLowerCase();
  852. // Exclude loopback
  853. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  854. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  855. if (type === 'wireguard' || name.startsWith('wg')) return false;
  856. // Exclude PPP / PPPoE
  857. if (type === 'ppp' || name.startsWith('ppp')) return false;
  858. // Exclude other Layer 3 tunnels and dummy devices
  859. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  860. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  861. return false;
  862. }
  863. // If name already contains a dot, it's already a sub-interface
  864. if (name.includes('.')) return false;
  865. return true;
  866. }
  867. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  868. function supportsDHCPClient(iface) {
  869. if (!iface) return false;
  870. const name = (iface.name || '').toLowerCase();
  871. const type = (iface.type || '').toLowerCase();
  872. const role = (iface.role || '').toLowerCase();
  873. // Exclude loopback
  874. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  875. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  876. if (type === 'wireguard' || name.startsWith('wg')) return false;
  877. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  878. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  879. // Exclude other Layer 3 tunnels and dummy devices
  880. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  881. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  882. return false;
  883. }
  884. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  885. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  886. if (isBridgePort) return false;
  887. return true;
  888. }
  889. // Expand / Collapse Handlers
  890. function toggleExpand(parentName) {
  891. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  892. if (childVlans.length === 0) {
  893. // Cannot expand an interface with no VLANs
  894. state.expandedParents.delete(parentName);
  895. return;
  896. }
  897. if (state.expandedParents.has(parentName)) {
  898. state.expandedParents.delete(parentName);
  899. } else {
  900. state.expandedParents.add(parentName);
  901. }
  902. renderInterfacesList();
  903. }
  904. function expandAllIfaces(expand) {
  905. if (expand) {
  906. (state.interfaces || []).forEach(i => {
  907. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  908. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  909. });
  910. } else {
  911. state.expandedParents.clear();
  912. }
  913. renderInterfacesList();
  914. }
  915. // =========================================================================
  916. // INTERFACE ROLE TAGS MANAGEMENT
  917. // =========================================================================
  918. const ROLE_COLORS = {
  919. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  920. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  921. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  922. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  923. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  924. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  925. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  926. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  927. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  928. };
  929. function getRoleBadge(roleName) {
  930. const name = roleName || 'LAN';
  931. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  932. const colorKey = (role?.color || 'blue').toLowerCase();
  933. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  934. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  935. }
  936. function switchIfaceSubTab(subTab) {
  937. state.activeIfaceSubTab = subTab;
  938. const treeTab = document.getElementById('ifaces-subtab-tree');
  939. const rolesTab = document.getElementById('ifaces-subtab-roles');
  940. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  941. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  942. if (subTab === 'roles') {
  943. treeTab?.classList.add('hidden');
  944. rolesTab?.classList.remove('hidden');
  945. if (btnRoles) {
  946. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  947. }
  948. if (btnTree) {
  949. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  950. }
  951. loadRoles();
  952. } else {
  953. rolesTab?.classList.add('hidden');
  954. treeTab?.classList.remove('hidden');
  955. if (btnTree) {
  956. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  957. }
  958. if (btnRoles) {
  959. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  960. }
  961. renderInterfacesList();
  962. }
  963. }
  964. async function loadRoles() {
  965. try {
  966. const res = await fetch(`${API_BASE}/roles`);
  967. if (res.ok) {
  968. state.roles = await res.json();
  969. const countEl = document.getElementById('badge-roles-count');
  970. if (countEl) countEl.innerText = (state.roles || []).length;
  971. renderRolesTable();
  972. populateRoleSelects();
  973. }
  974. } catch (err) {
  975. console.error('Failed to load role tags:', err);
  976. }
  977. }
  978. function renderRolesTable() {
  979. const tbody = document.getElementById('roles-table-body');
  980. const empty = document.getElementById('roles-empty-state');
  981. if (!tbody) return;
  982. const roles = state.roles || [];
  983. if (roles.length === 0) {
  984. tbody.innerHTML = '';
  985. empty?.classList.remove('hidden');
  986. return;
  987. }
  988. empty?.classList.add('hidden');
  989. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  990. if (tbody.dataset.sig === sig) return;
  991. tbody.dataset.sig = sig;
  992. tbody.innerHTML = roles.map(r => {
  993. const colorKey = (r.color || 'blue').toLowerCase();
  994. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  995. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  996. const ifacesChips = ifaces.length > 0
  997. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  998. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  999. return `
  1000. <tr class="hover:bg-slate-800/40 transition">
  1001. <td class="py-3 px-4">
  1002. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  1003. ${escapeHtml(r.name)}
  1004. </span>
  1005. </td>
  1006. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  1007. <span>${escapeHtml(r.name)}</span>
  1008. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  1009. </td>
  1010. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  1011. <span class="inline-flex items-center gap-1.5">
  1012. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  1013. <span>${escapeHtml(r.color || 'blue')}</span>
  1014. </span>
  1015. </td>
  1016. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  1017. <td class="py-3 px-4 font-sans">
  1018. <div class="flex flex-wrap items-center">
  1019. ${ifacesChips}
  1020. </div>
  1021. </td>
  1022. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  1023. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  1024. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1025. Edit
  1026. </button>
  1027. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  1028. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1029. Delete
  1030. </button>
  1031. </td>
  1032. </tr>
  1033. `;
  1034. }).join('');
  1035. }
  1036. function openRoleModal(id = null) {
  1037. const modal = document.getElementById('role-modal');
  1038. if (!modal) return;
  1039. const idInput = document.getElementById('role-modal-id');
  1040. const nameInput = document.getElementById('role-modal-name');
  1041. const colorSelect = document.getElementById('role-modal-color');
  1042. const descInput = document.getElementById('role-modal-desc');
  1043. const title = document.getElementById('role-modal-title');
  1044. if (id) {
  1045. const role = (state.roles || []).find(r => r.id === id);
  1046. if (role) {
  1047. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1048. if (idInput) idInput.value = role.id;
  1049. if (nameInput) nameInput.value = role.name;
  1050. if (colorSelect) colorSelect.value = role.color || 'blue';
  1051. if (descInput) descInput.value = role.description || '';
  1052. }
  1053. } else {
  1054. if (title) title.innerText = 'Add Role Tag';
  1055. if (idInput) idInput.value = '';
  1056. if (nameInput) nameInput.value = '';
  1057. if (colorSelect) colorSelect.value = 'blue';
  1058. if (descInput) descInput.value = '';
  1059. }
  1060. updateRoleModalPreview();
  1061. modal.classList.remove('hidden');
  1062. }
  1063. function closeRoleModal() {
  1064. const modal = document.getElementById('role-modal');
  1065. if (modal) modal.classList.add('hidden');
  1066. }
  1067. function updateRoleModalPreview() {
  1068. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1069. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1070. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1071. const preview = document.getElementById('role-modal-preview');
  1072. if (preview) {
  1073. preview.innerText = name;
  1074. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1075. }
  1076. }
  1077. async function submitSaveRole(e) {
  1078. e.preventDefault();
  1079. const id = document.getElementById('role-modal-id')?.value;
  1080. const name = document.getElementById('role-modal-name')?.value.trim();
  1081. const color = document.getElementById('role-modal-color')?.value;
  1082. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1083. if (!name) return;
  1084. try {
  1085. const payload = { id, name, color, description: desc };
  1086. const method = id ? 'PUT' : 'POST';
  1087. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1088. const res = await fetch(url, {
  1089. method,
  1090. headers: { 'Content-Type': 'application/json' },
  1091. body: JSON.stringify(payload)
  1092. });
  1093. if (res.ok) {
  1094. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1095. closeRoleModal();
  1096. await loadRoles();
  1097. fetchData(false);
  1098. } else {
  1099. const err = await res.json();
  1100. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1101. }
  1102. } catch (err) {
  1103. showToast('Error', err.message, 'error');
  1104. }
  1105. }
  1106. async function deleteRoleTag(id, name) {
  1107. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1108. try {
  1109. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1110. method: 'DELETE'
  1111. });
  1112. if (res.ok) {
  1113. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1114. await loadRoles();
  1115. fetchData(false);
  1116. } else {
  1117. const err = await res.json();
  1118. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1119. }
  1120. } catch (err) {
  1121. showToast('Error', err.message, 'error');
  1122. }
  1123. }
  1124. function populateRoleSelects(selectedRole = '') {
  1125. const ifaceSelect = document.getElementById('modal-iface-role');
  1126. const vlanSelect = document.getElementById('vlan-role');
  1127. const roles = state.roles || [];
  1128. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1129. if (ifaceSelect) {
  1130. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1131. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1132. ifaceSelect.innerHTML = optionsHtml;
  1133. ifaceSelect.dataset.optionsSig = optionsHtml;
  1134. }
  1135. if (currentVal) ifaceSelect.value = currentVal;
  1136. }
  1137. if (vlanSelect) {
  1138. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1139. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1140. vlanSelect.innerHTML = optionsHtml;
  1141. vlanSelect.dataset.optionsSig = optionsHtml;
  1142. }
  1143. if (currentVal) vlanSelect.value = currentVal;
  1144. }
  1145. }
  1146. // Filter and Render Hierarchical Interfaces List
  1147. function filterIfaces(filter) {
  1148. state.ifaceFilter = filter || 'all';
  1149. renderInterfacesList();
  1150. }
  1151. function renderInterfacesList() {
  1152. const tbody = document.getElementById('interfaces-tree-tbody');
  1153. const emptyState = document.getElementById('interfaces-empty-state');
  1154. const summary = document.getElementById('ifaces-list-summary');
  1155. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1156. const allIfaces = state.interfaces || [];
  1157. const allVlans = state.vlans || [];
  1158. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1159. const filteredParents = parentIfaces.filter(parent => {
  1160. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1161. if (query) {
  1162. const matchName = parent.name.toLowerCase().includes(query);
  1163. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1164. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1165. const matchType = (parent.type || '').toLowerCase().includes(query);
  1166. const matchVlan = childVlans.some(v =>
  1167. v.name.toLowerCase().includes(query) ||
  1168. String(v.vlan_id).includes(query) ||
  1169. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1170. (v.description || '').toLowerCase().includes(query)
  1171. );
  1172. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1173. }
  1174. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1175. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1176. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1177. return true;
  1178. });
  1179. if (summary) {
  1180. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1181. }
  1182. if (filteredParents.length === 0) {
  1183. emptyState?.classList.remove('hidden');
  1184. tbody.innerHTML = '';
  1185. return;
  1186. }
  1187. emptyState?.classList.add('hidden');
  1188. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1189. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1190. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1191. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1192. }).join(';');
  1193. if (tbody.dataset.sig === sig) {
  1194. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1195. }
  1196. tbody.dataset.sig = sig;
  1197. tbody.innerHTML = '';
  1198. filteredParents.forEach(parent => {
  1199. const isUp = parent.state === 'UP';
  1200. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1201. const hasVlans = childVlans.length > 0;
  1202. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1203. const canHaveVlan = supportsVLAN(parent);
  1204. const parentRow = document.createElement('tr');
  1205. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1206. parentRow.innerHTML = `
  1207. <td class="py-3 px-3 text-center">
  1208. ${hasVlans ? `
  1209. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1210. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1211. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1212. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1213. </svg>
  1214. </button>
  1215. ` : `
  1216. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1217. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1218. </div>
  1219. `}
  1220. </td>
  1221. <td class="py-3 px-4">
  1222. <div class="flex items-center space-x-2.5">
  1223. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  1224. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1225. </div>
  1226. <div>
  1227. <div class="flex items-center gap-2">
  1228. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1229. <span>${parent.name}</span>
  1230. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1231. </span>
  1232. ${hasVlans ? `
  1233. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  1234. ` : `
  1235. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  1236. `}
  1237. </div>
  1238. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1239. </div>
  1240. </div>
  1241. </td>
  1242. <td class="py-3 px-4 font-sans">
  1243. <div class="flex items-center gap-1.5">
  1244. ${getRoleBadge(parent.role || 'LAN')}
  1245. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1246. </div>
  1247. </td>
  1248. <td class="py-3 px-4">
  1249. ${parent.ipv4 && parent.ipv4.length > 0
  1250. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1251. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1252. }
  1253. ${(() => {
  1254. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1255. if (!c) return '';
  1256. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  1257. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1258. })()}
  1259. </td>
  1260. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1261. <div>${parent.mac || 'N/A'}</div>
  1262. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1263. </td>
  1264. <td class="py-3 px-4 text-[11px]">
  1265. <div class="flex items-center space-x-2">
  1266. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1267. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1268. </div>
  1269. </td>
  1270. <td class="py-3 px-4 font-sans">
  1271. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1272. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1273. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  1274. }" title="Click to toggle link status">
  1275. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1276. <span>${parent.state}</span>
  1277. </button>
  1278. </td>
  1279. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1280. ${(() => {
  1281. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1282. if (c) {
  1283. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  1284. }
  1285. if (!supportsDHCPClient(parent)) {
  1286. return '';
  1287. }
  1288. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  1289. })()}
  1290. ${canHaveVlan ? `
  1291. <button onclick="openVlanModal('${parent.name}')"
  1292. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  1293. + Add VLAN
  1294. </button>
  1295. ` : ''}
  1296. <button onclick="openIfaceModal('${parent.name}')"
  1297. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  1298. Edit
  1299. </button>
  1300. </td>
  1301. `;
  1302. tbody.appendChild(parentRow);
  1303. if (isExpanded) {
  1304. const drawerRow = document.createElement('tr');
  1305. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1306. const drawerCell = document.createElement('td');
  1307. drawerCell.colSpan = 8;
  1308. drawerCell.className = 'p-0';
  1309. drawerCell.innerHTML = `
  1310. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  1311. <div class="flex items-center justify-between mb-3">
  1312. <div class="flex items-center space-x-3">
  1313. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1314. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1315. </span>
  1316. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1317. ${childVlans.length} Attached
  1318. </span>
  1319. </div>
  1320. <button onclick="openVlanModal('${parent.name}')"
  1321. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  1322. <span>+ Create VLAN on ${parent.name}</span>
  1323. </button>
  1324. </div>
  1325. ${childVlans.length === 0 ? `
  1326. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1327. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  1328. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  1329. <span>+ Create Your First VLAN on ${parent.name}</span>
  1330. </button>
  1331. </div>
  1332. ` : `
  1333. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1334. <table class="w-full text-left text-xs font-mono">
  1335. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1336. <tr>
  1337. <th class="py-2.5 px-4">VLAN ID</th>
  1338. <th class="py-2.5 px-4">Interface Device</th>
  1339. <th class="py-2.5 px-4">Subnet Gateway</th>
  1340. <th class="py-2.5 px-4">Role / Alias</th>
  1341. <th class="py-2.5 px-4">MTU</th>
  1342. <th class="py-2.5 px-4">Throughput</th>
  1343. <th class="py-2.5 px-4">Status</th>
  1344. <th class="py-2.5 px-4 text-right">Actions</th>
  1345. </tr>
  1346. </thead>
  1347. <tbody class="divide-y divide-slate-800/70">
  1348. ${childVlans.map(v => {
  1349. const isVlanUp = v.state === 'UP';
  1350. return `
  1351. <tr class="hover:bg-slate-800/40 transition">
  1352. <td class="py-2.5 px-4">
  1353. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1354. VLAN ${v.vlan_id}
  1355. </span>
  1356. </td>
  1357. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1358. <span class="text-cyan-500">└─</span>
  1359. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1360. <span>${v.name}</span>
  1361. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1362. </span>
  1363. </td>
  1364. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1365. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1366. ${(() => {
  1367. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1368. if (!c) return '';
  1369. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  1370. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1371. })()}
  1372. </td>
  1373. <td class="py-2.5 px-4 font-sans text-slate-300">
  1374. <div class="flex items-center gap-1.5">
  1375. ${getRoleBadge(v.role || 'LAN')}
  1376. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1377. </div>
  1378. </td>
  1379. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1380. <td class="py-2.5 px-4 text-[11px]">
  1381. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1382. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1383. </td>
  1384. <td class="py-2.5 px-4 font-sans">
  1385. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1386. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1387. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1388. }">
  1389. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1390. <span>${v.state}</span>
  1391. </button>
  1392. </td>
  1393. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1394. ${(() => {
  1395. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1396. if (c) {
  1397. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  1398. }
  1399. if (!supportsDHCPClient(v)) {
  1400. return '';
  1401. }
  1402. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  1403. })()}
  1404. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  1405. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  1406. </td>
  1407. </tr>
  1408. `;
  1409. }).join('')}
  1410. </tbody>
  1411. </table>
  1412. </div>
  1413. `}
  1414. </div>
  1415. `;
  1416. drawerRow.appendChild(drawerCell);
  1417. tbody.appendChild(drawerRow);
  1418. }
  1419. });
  1420. }
  1421. // Render VLANs Dedicated View
  1422. function renderVlansList() {
  1423. const tbody = document.getElementById('vlans-table-body');
  1424. if (!tbody) return;
  1425. const emptyState = document.getElementById('vlans-empty-state');
  1426. const countBadge = document.getElementById('vlans-table-count');
  1427. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1428. const allVlans = state.vlans || [];
  1429. if (countBadge) countBadge.innerText = allVlans.length;
  1430. const filtered = allVlans.filter(v => {
  1431. if (!query) return true;
  1432. return v.name.toLowerCase().includes(query) ||
  1433. String(v.vlan_id).includes(query) ||
  1434. (v.description || '').toLowerCase().includes(query) ||
  1435. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1436. });
  1437. if (allVlans.length === 0) {
  1438. emptyState.classList.remove('hidden');
  1439. tbody.innerHTML = '';
  1440. return;
  1441. }
  1442. emptyState.classList.add('hidden');
  1443. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1444. if (tbody.dataset.sig === sig) return;
  1445. tbody.dataset.sig = sig;
  1446. tbody.innerHTML = '';
  1447. filtered.forEach(v => {
  1448. const isUp = v.state === 'UP';
  1449. const tr = document.createElement('tr');
  1450. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1451. tr.innerHTML = `
  1452. <td class="py-3 px-4">
  1453. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1454. VLAN ${v.vlan_id}
  1455. </span>
  1456. </td>
  1457. <td class="py-3 px-4 font-bold text-white">
  1458. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1459. <span>${v.name}</span>
  1460. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1461. </span>
  1462. </td>
  1463. <td class="py-3 px-4 text-slate-300">
  1464. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1465. </td>
  1466. <td class="py-3 px-4 text-emerald-400 font-medium">
  1467. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1468. </td>
  1469. <td class="py-3 px-4 text-slate-300 font-sans">
  1470. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1471. </td>
  1472. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1473. <td class="py-3 px-4 font-sans">
  1474. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1475. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1476. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1477. }">
  1478. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1479. <span>${v.state}</span>
  1480. </button>
  1481. </td>
  1482. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1483. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1484. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1485. </td>
  1486. `;
  1487. tbody.appendChild(tr);
  1488. });
  1489. }
  1490. // Toggle interface UP / DOWN
  1491. async function toggleInterfaceState(name, newState) {
  1492. try {
  1493. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1494. method: 'POST',
  1495. headers: { 'Content-Type': 'application/json' },
  1496. body: JSON.stringify({ state: newState })
  1497. });
  1498. const data = await res.json();
  1499. if (res.ok) {
  1500. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1501. fetchData(false);
  1502. } else {
  1503. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1504. }
  1505. } catch (err) {
  1506. showToast('Error', err.message, 'error');
  1507. }
  1508. }
  1509. // ---------------- MikroTik Flag & Utilities ----------------
  1510. function renderMikroTikFlag(running, disabled) {
  1511. if (running) {
  1512. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1513. }
  1514. if (disabled) {
  1515. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1516. }
  1517. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1518. }
  1519. function copyToClipboard(text, label = 'Text') {
  1520. navigator.clipboard.writeText(text).then(() => {
  1521. showToast('Copied', `${label} copied to clipboard`, 'success');
  1522. }).catch(() => {
  1523. prompt('Copy value:', text);
  1524. });
  1525. }
  1526. // ======================== PPP Profiles Shared Helper ========================
  1527. async function fetchPPPProfilesList() {
  1528. try {
  1529. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1530. if (res.ok) {
  1531. state.pppProfiles = await res.json();
  1532. }
  1533. } catch (err) {
  1534. console.error('Failed to load PPP profiles:', err);
  1535. }
  1536. }
  1537. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1538. const sel = document.getElementById(selectId);
  1539. if (!sel) return;
  1540. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1541. { name: 'default', use_encryption: 'no' },
  1542. { name: 'default-encryption', use_encryption: 'required' }
  1543. ];
  1544. sel.innerHTML = '';
  1545. profiles.forEach(p => {
  1546. const opt = document.createElement('option');
  1547. opt.value = p.name;
  1548. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1549. opt.innerText = `${p.name}${encBadge}`;
  1550. sel.appendChild(opt);
  1551. });
  1552. if (selectedVal) {
  1553. sel.value = selectedVal;
  1554. } else {
  1555. sel.value = defaultVal;
  1556. }
  1557. if (!sel.value && sel.options.length > 0) {
  1558. sel.selectedIndex = 0;
  1559. }
  1560. }
  1561. // ======================== PPPoE Multi-Instance ========================
  1562. async function loadPPPoE(populateInputs = true) {
  1563. try {
  1564. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1565. await fetchPPPProfilesList();
  1566. }
  1567. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1568. const list = await res.json();
  1569. state.pppoeList = Array.isArray(list) ? list : [];
  1570. const badge = document.getElementById('pppoe-count-badge');
  1571. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1572. const tbody = document.getElementById('pppoe-table-body');
  1573. const empty = document.getElementById('pppoe-empty');
  1574. if (!tbody) return;
  1575. tbody.innerHTML = '';
  1576. if (state.pppoeList.length === 0) {
  1577. if (empty) empty.classList.remove('hidden');
  1578. } else {
  1579. if (empty) empty.classList.add('hidden');
  1580. state.pppoeList.forEach(inst => {
  1581. const tr = document.createElement('tr');
  1582. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1583. tr.innerHTML = `
  1584. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1585. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1586. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1587. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1588. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1589. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1590. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1591. <td class="py-2.5 px-3 text-center">
  1592. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1593. ${inst.default_route ? 'Yes' : 'No'}
  1594. </span>
  1595. </td>
  1596. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1597. ${inst.running ? `
  1598. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1599. ` : `
  1600. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1601. `}
  1602. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1603. ${inst.disabled ? 'Enable' : 'Disable'}
  1604. </button>
  1605. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1606. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1607. </td>
  1608. `;
  1609. tbody.appendChild(tr);
  1610. });
  1611. }
  1612. } catch (err) {
  1613. console.error('Failed to load PPPoE:', err);
  1614. }
  1615. }
  1616. function openAddPPPoEModal() {
  1617. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1618. document.getElementById('pppoe-modal-edit-orig').value = '';
  1619. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1620. document.getElementById('pppoe-modal-name').readOnly = false;
  1621. document.getElementById('pppoe-modal-user').value = '';
  1622. document.getElementById('pppoe-modal-pass').value = '';
  1623. document.getElementById('pppoe-modal-service').value = '';
  1624. document.getElementById('pppoe-modal-mtu').value = '1492';
  1625. document.getElementById('pppoe-modal-defroute').checked = true;
  1626. document.getElementById('pppoe-modal-reconnect').checked = true;
  1627. document.getElementById('pppoe-modal-disabled').checked = false;
  1628. // Populate profiles
  1629. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1630. // Populate interfaces
  1631. const sel = document.getElementById('pppoe-modal-iface');
  1632. sel.innerHTML = '';
  1633. (state.interfaces || []).forEach(i => {
  1634. if (i.name === 'lo') return;
  1635. const opt = document.createElement('option');
  1636. opt.value = i.name;
  1637. opt.innerText = `${i.name} (${i.role || i.type})`;
  1638. sel.appendChild(opt);
  1639. });
  1640. document.getElementById('pppoe-modal').classList.remove('hidden');
  1641. }
  1642. function openEditPPPoEModal(name) {
  1643. const inst = (state.pppoeList || []).find(i => i.name === name);
  1644. if (!inst) return;
  1645. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1646. document.getElementById('pppoe-modal-edit-orig').value = name;
  1647. document.getElementById('pppoe-modal-name').value = inst.name;
  1648. document.getElementById('pppoe-modal-name').readOnly = true;
  1649. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1650. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1651. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1652. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1653. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1654. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1655. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1656. // Populate profiles
  1657. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1658. const sel = document.getElementById('pppoe-modal-iface');
  1659. sel.innerHTML = '';
  1660. (state.interfaces || []).forEach(i => {
  1661. if (i.name === 'lo') return;
  1662. const opt = document.createElement('option');
  1663. opt.value = i.name;
  1664. opt.innerText = `${i.name} (${i.role || i.type})`;
  1665. if (i.name === inst.interface) opt.selected = true;
  1666. sel.appendChild(opt);
  1667. });
  1668. document.getElementById('pppoe-modal').classList.remove('hidden');
  1669. }
  1670. function closePPPoEModal() {
  1671. document.getElementById('pppoe-modal').classList.add('hidden');
  1672. }
  1673. async function submitSavePPPoE(e) {
  1674. e.preventDefault();
  1675. const name = document.getElementById('pppoe-modal-name').value.trim();
  1676. const iface = document.getElementById('pppoe-modal-iface').value;
  1677. const user = document.getElementById('pppoe-modal-user').value.trim();
  1678. const pass = document.getElementById('pppoe-modal-pass').value;
  1679. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1680. const service = document.getElementById('pppoe-modal-service').value.trim();
  1681. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1682. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1683. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1684. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1685. try {
  1686. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1687. method: 'POST',
  1688. headers: { 'Content-Type': 'application/json' },
  1689. body: JSON.stringify({
  1690. name,
  1691. interface: iface,
  1692. username: user,
  1693. password: pass,
  1694. profile: profile,
  1695. service_name: service,
  1696. mtu,
  1697. default_route: defRoute,
  1698. auto_reconnect: reconnect,
  1699. disabled
  1700. })
  1701. });
  1702. if (res.ok) {
  1703. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1704. closePPPoEModal();
  1705. loadPPPoE(false);
  1706. fetchData(false);
  1707. } else {
  1708. const err = await res.json();
  1709. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1710. }
  1711. } catch (err) {
  1712. showToast('Error', err.message, 'error');
  1713. }
  1714. }
  1715. async function connectPPPoEInstance(name) {
  1716. try {
  1717. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1718. if (res.ok) {
  1719. showToast('Connecting', `Dialing ${name}...`, 'info');
  1720. setTimeout(() => loadPPPoE(false), 2000);
  1721. }
  1722. } catch (err) {
  1723. showToast('Error', err.message, 'error');
  1724. }
  1725. }
  1726. async function disconnectPPPoEInstance(name) {
  1727. try {
  1728. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1729. if (res.ok) {
  1730. showToast('Disconnected', `${name} session terminated`, 'info');
  1731. setTimeout(() => loadPPPoE(false), 1000);
  1732. }
  1733. } catch (err) {
  1734. showToast('Error', err.message, 'error');
  1735. }
  1736. }
  1737. async function togglePPPoEState(name, enable) {
  1738. try {
  1739. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1740. method: 'POST',
  1741. headers: { 'Content-Type': 'application/json' },
  1742. body: JSON.stringify({ enabled: enable })
  1743. });
  1744. if (res.ok) {
  1745. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1746. loadPPPoE(false);
  1747. }
  1748. } catch (err) {
  1749. showToast('Error', err.message, 'error');
  1750. }
  1751. }
  1752. async function deletePPPoEInstance(name) {
  1753. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1754. try {
  1755. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1756. if (res.ok) {
  1757. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1758. loadPPPoE(false);
  1759. fetchData(false);
  1760. }
  1761. } catch (err) {
  1762. showToast('Error', err.message, 'error');
  1763. }
  1764. }
  1765. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1766. state.wgSubTab = 'ifaces';
  1767. function switchWGSubTab(tab) {
  1768. state.wgSubTab = tab;
  1769. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1770. const peersPanel = document.getElementById('wg-subtab-peers');
  1771. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1772. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1773. if (tab === 'ifaces') {
  1774. ifacesPanel?.classList.remove('hidden');
  1775. peersPanel?.classList.add('hidden');
  1776. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1777. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1778. } else {
  1779. ifacesPanel?.classList.add('hidden');
  1780. peersPanel?.classList.remove('hidden');
  1781. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1782. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1783. renderWGPeers();
  1784. }
  1785. }
  1786. async function loadWireGuard(populateInputs = true) {
  1787. try {
  1788. const [ifacesRes, peersRes] = await Promise.all([
  1789. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1790. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1791. ]);
  1792. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1793. const peers = peersRes.ok ? await peersRes.json() : [];
  1794. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1795. state.wgPeers = Array.isArray(peers) ? peers : [];
  1796. // Badges
  1797. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1798. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1799. const peersCountBadge = document.getElementById('wg-peers-count');
  1800. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1801. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1802. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1803. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1804. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1805. // Render Interfaces
  1806. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1807. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1808. if (ifacesTbody) {
  1809. ifacesTbody.innerHTML = '';
  1810. if (state.wgInterfaces.length === 0) {
  1811. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1812. } else {
  1813. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1814. state.wgInterfaces.forEach(iface => {
  1815. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1816. const tr = document.createElement('tr');
  1817. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1818. tr.innerHTML = `
  1819. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1820. <td class="py-2.5 px-3">
  1821. <div class="flex items-center gap-1.5">
  1822. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1823. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1824. </div>
  1825. </td>
  1826. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1827. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1828. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1829. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1830. ${(iface.public_key || '').substring(0, 10)}... 📋
  1831. </span>
  1832. </td>
  1833. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1834. <td class="py-2.5 px-3 text-center">
  1835. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1836. </td>
  1837. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1838. ${iface.running ? `
  1839. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1840. ` : `
  1841. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1842. `}
  1843. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1844. ${iface.disabled ? 'Enable' : 'Disable'}
  1845. </button>
  1846. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1847. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1848. </td>
  1849. `;
  1850. ifacesTbody.appendChild(tr);
  1851. });
  1852. }
  1853. }
  1854. // Populate filter dropdown in peers tab
  1855. const filterSel = document.getElementById('wg-peers-filter-iface');
  1856. if (filterSel) {
  1857. const currentVal = filterSel.value;
  1858. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1859. state.wgInterfaces.forEach(i => {
  1860. const opt = document.createElement('option');
  1861. opt.value = i.name;
  1862. opt.innerText = i.name;
  1863. if (i.name === currentVal) opt.selected = true;
  1864. filterSel.appendChild(opt);
  1865. });
  1866. }
  1867. renderWGPeers();
  1868. } catch (err) {
  1869. console.error('Failed to load WireGuard:', err);
  1870. }
  1871. }
  1872. function formatWGPeerEndpoint(address, port) {
  1873. if (!address || address === '(none)') return '--';
  1874. let addr = address.trim();
  1875. let p = port || 0;
  1876. while (addr.includes(':') && !addr.startsWith('[')) {
  1877. const lastColon = addr.lastIndexOf(':');
  1878. const maybePort = addr.substring(lastColon + 1);
  1879. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1880. if (!p) p = parseInt(maybePort, 10);
  1881. addr = addr.substring(0, lastColon);
  1882. } else {
  1883. break;
  1884. }
  1885. }
  1886. return p ? `${addr}:${p}` : addr;
  1887. }
  1888. function renderWGPeers() {
  1889. const filterSel = document.getElementById('wg-peers-filter-iface');
  1890. const selectedIface = filterSel ? filterSel.value : '';
  1891. const tbody = document.getElementById('wg-peers-table-body');
  1892. const empty = document.getElementById('wg-peers-empty');
  1893. if (!tbody) return;
  1894. tbody.innerHTML = '';
  1895. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1896. if (filtered.length === 0) {
  1897. if (empty) empty.classList.remove('hidden');
  1898. } else {
  1899. if (empty) empty.classList.add('hidden');
  1900. filtered.forEach(p => {
  1901. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1902. const tr = document.createElement('tr');
  1903. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1904. tr.innerHTML = `
  1905. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1906. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1907. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1908. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1909. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1910. ${(p.public_key || '').substring(0, 10)}... 📋
  1911. </span>
  1912. </td>
  1913. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1914. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1915. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1916. <td class="py-2.5 px-3 font-mono text-[11px]">
  1917. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1918. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1919. </td>
  1920. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1921. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1922. ${p.disabled ? 'Enable' : 'Disable'}
  1923. </button>
  1924. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1925. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1926. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1927. </td>
  1928. `;
  1929. tbody.appendChild(tr);
  1930. });
  1931. }
  1932. }
  1933. function openAddWGInterfaceModal() {
  1934. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1935. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1936. const nameEl = document.getElementById('wg-iface-modal-name');
  1937. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1938. nameEl.readOnly = false;
  1939. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1940. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1941. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1942. document.getElementById('wg-iface-modal-comment').value = '';
  1943. document.getElementById('wg-iface-modal-pubkey').value = '';
  1944. document.getElementById('wg-iface-modal-privkey').value = '';
  1945. document.getElementById('wg-iface-modal-disabled').checked = false;
  1946. generateWGInterfaceKeys();
  1947. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1948. }
  1949. function openEditWGInterfaceModal(name) {
  1950. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1951. if (!iface) return;
  1952. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1953. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1954. const nameEl = document.getElementById('wg-iface-modal-name');
  1955. nameEl.value = iface.name;
  1956. nameEl.readOnly = false; // ALLOW RENAMING
  1957. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1958. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1959. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1960. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1961. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1962. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1963. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1964. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1965. }
  1966. function closeAddWGInterfaceModal() {
  1967. document.getElementById('wg-iface-modal').classList.add('hidden');
  1968. }
  1969. async function generateWGInterfaceKeys() {
  1970. try {
  1971. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1972. const keys = await res.json();
  1973. if (res.ok) {
  1974. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1975. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1976. }
  1977. } catch (err) {
  1978. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1979. }
  1980. }
  1981. async function onWGInterfacePrivKeyInput() {
  1982. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1983. if (!privKey) return;
  1984. try {
  1985. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1986. method: 'POST',
  1987. headers: { 'Content-Type': 'application/json' },
  1988. body: JSON.stringify({ private_key: privKey })
  1989. });
  1990. if (res.ok) {
  1991. const data = await res.json();
  1992. if (data.public_key) {
  1993. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1994. }
  1995. }
  1996. } catch (err) {
  1997. // Ignore while typing
  1998. }
  1999. }
  2000. function toggleWGPrivKeyVisibility() {
  2001. const el = document.getElementById('wg-iface-modal-privkey');
  2002. const btn = document.getElementById('btn-toggle-wg-privkey');
  2003. if (el.type === 'password') {
  2004. el.type = 'text';
  2005. btn.innerText = '🙈 Hide';
  2006. } else {
  2007. el.type = 'password';
  2008. btn.innerText = '👁️ Show';
  2009. }
  2010. }
  2011. function copyWGInterfacePubKey() {
  2012. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  2013. if (pub) copyToClipboard(pub, 'Interface Public Key');
  2014. }
  2015. async function submitSaveWGInterface(e) {
  2016. e.preventDefault();
  2017. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  2018. const name = document.getElementById('wg-iface-modal-name').value.trim();
  2019. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  2020. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  2021. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  2022. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  2023. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  2024. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  2025. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  2026. try {
  2027. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  2028. method: 'POST',
  2029. headers: { 'Content-Type': 'application/json' },
  2030. body: JSON.stringify({
  2031. orig_name: origName,
  2032. name,
  2033. listen_port: port,
  2034. address: addr,
  2035. mtu,
  2036. comment,
  2037. public_key: pub,
  2038. private_key: priv,
  2039. disabled
  2040. })
  2041. });
  2042. const data = await res.json();
  2043. if (res.ok) {
  2044. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2045. closeAddWGInterfaceModal();
  2046. loadWireGuard(false);
  2047. fetchData(false);
  2048. } else {
  2049. showToast('Error', data.error || 'Failed to save interface', 'error');
  2050. }
  2051. } catch (err) {
  2052. showToast('Error', err.message, 'error');
  2053. }
  2054. }
  2055. async function startWGInterface(name) {
  2056. try {
  2057. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2058. if (res.ok) {
  2059. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2060. loadWireGuard(false);
  2061. fetchData(false);
  2062. }
  2063. } catch (err) {
  2064. showToast('Error', err.message, 'error');
  2065. }
  2066. }
  2067. async function stopWGInterface(name) {
  2068. try {
  2069. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2070. if (res.ok) {
  2071. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2072. loadWireGuard(false);
  2073. fetchData(false);
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function toggleWGInterfaceState(name, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ enabled: enable })
  2085. });
  2086. if (res.ok) {
  2087. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2088. loadWireGuard(false);
  2089. fetchData(false);
  2090. }
  2091. } catch (err) {
  2092. showToast('Error', err.message, 'error');
  2093. }
  2094. }
  2095. async function deleteWGInterface(name) {
  2096. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2097. try {
  2098. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2099. if (res.ok) {
  2100. showToast('Deleted', `Interface ${name} removed`, 'success');
  2101. loadWireGuard(false);
  2102. fetchData(false);
  2103. }
  2104. } catch (err) {
  2105. showToast('Error', err.message, 'error');
  2106. }
  2107. }
  2108. function populateWGPeerIfaceSelect(selectedIface = '') {
  2109. const sel = document.getElementById('wg-peer-modal-iface');
  2110. if (!sel) return;
  2111. sel.innerHTML = '';
  2112. (state.wgInterfaces || []).forEach(i => {
  2113. const opt = document.createElement('option');
  2114. opt.value = i.name;
  2115. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2116. if (i.name === selectedIface) opt.selected = true;
  2117. sel.appendChild(opt);
  2118. });
  2119. }
  2120. function openAddWGPeerModal() {
  2121. if ((state.wgInterfaces || []).length === 0) {
  2122. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2123. openAddWGInterfaceModal();
  2124. return;
  2125. }
  2126. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2127. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2128. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2129. populateWGPeerIfaceSelect();
  2130. document.getElementById('wg-peer-modal-name').value = '';
  2131. document.getElementById('wg-peer-modal-pubkey').value = '';
  2132. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2133. document.getElementById('wg-peer-modal-endpoint').value = '';
  2134. document.getElementById('wg-peer-modal-port').value = '';
  2135. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2136. document.getElementById('wg-peer-modal-preshared').value = '';
  2137. document.getElementById('wg-peer-modal-disabled').checked = false;
  2138. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2139. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2140. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2141. }
  2142. function openEditWGPeerModal(ifaceName, pubKey) {
  2143. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2144. if (!peer) {
  2145. showToast('Not Found', 'Peer not found', 'warning');
  2146. return;
  2147. }
  2148. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2149. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2150. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2151. populateWGPeerIfaceSelect(peer.interface);
  2152. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2153. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2154. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2155. let epHost = (peer.endpoint_address || '').trim();
  2156. let epPort = peer.endpoint_port || '';
  2157. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2158. const lastColon = epHost.lastIndexOf(':');
  2159. const maybePort = epHost.substring(lastColon + 1);
  2160. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2161. if (!epPort) epPort = parseInt(maybePort, 10);
  2162. epHost = epHost.substring(0, lastColon);
  2163. } else {
  2164. break;
  2165. }
  2166. }
  2167. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2168. document.getElementById('wg-peer-modal-port').value = epPort;
  2169. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2170. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2171. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2172. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2173. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2174. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2175. }
  2176. function closeAddWGPeerModal() {
  2177. document.getElementById('wg-peer-modal').classList.add('hidden');
  2178. }
  2179. async function generatePeerKeypairHelper() {
  2180. try {
  2181. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2182. const keys = await res.json();
  2183. if (res.ok) {
  2184. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2185. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2186. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2187. checkWGPeerKeyValidity();
  2188. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2189. }
  2190. } catch (err) {
  2191. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2192. }
  2193. }
  2194. function copyGeneratedPeerPrivKey() {
  2195. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2196. if (priv) copyToClipboard(priv, 'Client Private Key');
  2197. }
  2198. async function generatePeerPSK() {
  2199. try {
  2200. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2201. const keys = await res.json();
  2202. if (res.ok && keys.private_key) {
  2203. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2204. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2205. }
  2206. } catch (err) {
  2207. showToast('Error', err.message, 'error');
  2208. }
  2209. }
  2210. function checkWGPeerKeyValidity() {
  2211. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2212. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2213. const warningEl = document.getElementById('wg-peer-key-warning');
  2214. if (!warningEl) return;
  2215. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2216. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2217. warningEl.classList.remove('hidden');
  2218. } else {
  2219. warningEl.classList.add('hidden');
  2220. }
  2221. }
  2222. async function submitSaveWGPeer(e) {
  2223. e.preventDefault();
  2224. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2225. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2226. const iface = document.getElementById('wg-peer-modal-iface').value;
  2227. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2228. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2229. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2230. .split(',')
  2231. .map(s => s.trim())
  2232. .filter(s => s.length > 0);
  2233. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2234. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2235. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2236. const lastColon = epHost.lastIndexOf(':');
  2237. const maybePort = epHost.substring(lastColon + 1);
  2238. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2239. if (!epPort) epPort = parseInt(maybePort, 10);
  2240. epHost = epHost.substring(0, lastColon);
  2241. } else {
  2242. break;
  2243. }
  2244. }
  2245. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2246. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2247. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2248. // Validation
  2249. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2250. if (targetIface && targetIface.public_key === pub) {
  2251. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2252. return;
  2253. }
  2254. try {
  2255. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2256. method: 'POST',
  2257. headers: { 'Content-Type': 'application/json' },
  2258. body: JSON.stringify({
  2259. orig_interface: origIface,
  2260. orig_public_key: origPubKey,
  2261. interface: iface,
  2262. name,
  2263. public_key: pub,
  2264. allowed_ips: allowed,
  2265. endpoint_address: epHost,
  2266. endpoint_port: epPort,
  2267. persistent_keepalive: keepalive,
  2268. preshared_key: psk,
  2269. disabled
  2270. })
  2271. });
  2272. const data = await res.json();
  2273. if (res.ok) {
  2274. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2275. closeAddWGPeerModal();
  2276. loadWireGuard(false);
  2277. } else {
  2278. showToast('Error', data.error || 'Failed to save peer', 'error');
  2279. }
  2280. } catch (err) {
  2281. showToast('Error', err.message, 'error');
  2282. }
  2283. }
  2284. async function toggleWGPeerState(iface, pubkey, enable) {
  2285. try {
  2286. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2287. method: 'POST',
  2288. headers: { 'Content-Type': 'application/json' },
  2289. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2290. });
  2291. const data = await res.json();
  2292. if (res.ok) {
  2293. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2294. loadWireGuard(false);
  2295. } else {
  2296. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2297. }
  2298. } catch (err) {
  2299. showToast('Error', err.message, 'error');
  2300. }
  2301. }
  2302. async function deleteWGPeer(iface, pubkey) {
  2303. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2304. try {
  2305. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2306. method: 'POST',
  2307. headers: { 'Content-Type': 'application/json' },
  2308. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2309. });
  2310. const data = await res.json();
  2311. if (res.ok) {
  2312. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2313. loadWireGuard(false);
  2314. } else {
  2315. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2316. }
  2317. } catch (err) {
  2318. showToast('Error', err.message, 'error');
  2319. }
  2320. }
  2321. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2322. function switchIpsecModalTab(tab) {
  2323. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2324. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2325. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2326. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2327. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2328. if (tab === 'p1') {
  2329. if (p1Tab) {
  2330. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  2331. }
  2332. if (p2Tab) {
  2333. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2334. }
  2335. if (p1Content) p1Content.classList.remove('hidden');
  2336. if (p2Content) p2Content.classList.add('hidden');
  2337. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2338. } else {
  2339. if (p1Tab) {
  2340. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2341. }
  2342. if (p2Tab) {
  2343. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  2344. }
  2345. if (p1Content) p1Content.classList.add('hidden');
  2346. if (p2Content) p2Content.classList.remove('hidden');
  2347. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2348. }
  2349. }
  2350. function toggleIpsecPhaseStep() {
  2351. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2352. if (p1Content && !p1Content.classList.contains('hidden')) {
  2353. switchIpsecModalTab('p2');
  2354. } else {
  2355. switchIpsecModalTab('p1');
  2356. }
  2357. }
  2358. function toggleIpsecPskVisibility() {
  2359. const pskInput = document.getElementById('ipsec-modal-psk');
  2360. if (!pskInput) return;
  2361. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2362. }
  2363. function addIpsecLocalSubnet(val = '') {
  2364. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2365. if (!container) return;
  2366. const row = document.createElement('div');
  2367. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2368. row.innerHTML = `
  2369. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  2370. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  2371. `;
  2372. container.appendChild(row);
  2373. }
  2374. function addIpsecRemoteSubnet(val = '') {
  2375. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2376. if (!container) return;
  2377. const row = document.createElement('div');
  2378. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2379. row.innerHTML = `
  2380. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  2381. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  2382. `;
  2383. container.appendChild(row);
  2384. }
  2385. function updateIpsecEspProposalFromPFS(val) {
  2386. const prop = document.getElementById('ipsec-modal-espprop');
  2387. if (!prop) return;
  2388. if (val === 'none') {
  2389. prop.value = 'aes256-sha256,aes128-sha256,default';
  2390. } else {
  2391. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2392. }
  2393. }
  2394. function updateIpsecIkeProposalFromDH(dh) {
  2395. const el = document.getElementById('ipsec-modal-ikeprop');
  2396. if (el) {
  2397. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2398. }
  2399. }
  2400. function safeSetVal(id, val) {
  2401. const el = document.getElementById(id);
  2402. if (el) el.value = val;
  2403. }
  2404. function safeSetChecked(id, val) {
  2405. const el = document.getElementById(id);
  2406. if (el) el.checked = !!val;
  2407. }
  2408. function safeGetVal(id, def = '') {
  2409. const el = document.getElementById(id);
  2410. return el ? el.value : def;
  2411. }
  2412. async function loadIPSec(populateInputs = true) {
  2413. try {
  2414. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2415. const list = await res.json();
  2416. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2417. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2418. const badge = document.getElementById('ipsec-sas-badge');
  2419. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2420. const tbody = document.getElementById('ipsec-table-body');
  2421. const empty = document.getElementById('ipsec-empty');
  2422. if (!tbody) return;
  2423. tbody.innerHTML = '';
  2424. if (state.ipsecTunnels.length === 0) {
  2425. if (empty) empty.classList.remove('hidden');
  2426. } else {
  2427. if (empty) empty.classList.add('hidden');
  2428. state.ipsecTunnels.forEach(c => {
  2429. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2430. const tr = document.createElement('tr');
  2431. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2432. // Local subnets tags
  2433. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2434. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2435. // Remote subnets tags
  2436. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2437. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2438. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2439. const p2Name = c.phase2_name || `${c.name}_p2`;
  2440. tr.innerHTML = `
  2441. <td class="py-2.5 px-3 text-center">
  2442. ${isEstablished ? `
  2443. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2444. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2445. <span>UP</span>
  2446. </span>
  2447. ` : (c.disabled ? `
  2448. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2449. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2450. <span>DOWN</span>
  2451. </span>
  2452. ` : `
  2453. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2454. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2455. <span>IDLE</span>
  2456. </span>
  2457. `)}
  2458. </td>
  2459. <td class="py-2.5 px-4 font-bold text-white">
  2460. <div class="flex items-center gap-2">
  2461. <span class="text-amber-400">🛡</span>
  2462. <div>
  2463. <div>${escapeHtml(c.name)}</div>
  2464. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2465. </div>
  2466. </div>
  2467. </td>
  2468. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2469. <td class="py-2.5 px-4 font-sans">
  2470. <div class="flex items-center gap-1.5">
  2471. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2472. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2473. </div>
  2474. </td>
  2475. <td class="py-2.5 px-4">
  2476. <div class="space-y-1">
  2477. <div class="flex items-center flex-wrap gap-1">
  2478. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2479. ${localBadges}
  2480. </div>
  2481. <div class="flex items-center flex-wrap gap-1">
  2482. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2483. ${remoteBadges}
  2484. </div>
  2485. </div>
  2486. </td>
  2487. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2488. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2489. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2490. </div>
  2491. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2492. </td>
  2493. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2494. ${isEstablished ? `
  2495. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2496. ` : `
  2497. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2498. `}
  2499. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2500. ${c.disabled ? 'Enable' : 'Disable'}
  2501. </button>
  2502. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2503. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2504. </td>
  2505. `;
  2506. tbody.appendChild(tr);
  2507. });
  2508. }
  2509. } catch (err) {
  2510. console.error('Failed to load IPSec:', err);
  2511. }
  2512. }
  2513. function openAddIPSecModal() {
  2514. const modal = document.getElementById('ipsec-modal');
  2515. if (!modal) return;
  2516. const title = document.getElementById('ipsec-modal-title');
  2517. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2518. // Phase 1 Fields
  2519. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2520. const nameEl = document.getElementById('ipsec-modal-name');
  2521. if (nameEl) nameEl.readOnly = false;
  2522. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2523. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2524. safeSetVal('ipsec-modal-remotegw', '');
  2525. safeSetVal('ipsec-modal-localaddrs', '');
  2526. safeSetVal('ipsec-modal-comments', '');
  2527. safeSetVal('ipsec-modal-psk', '');
  2528. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2529. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2530. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2531. safeSetVal('ipsec-modal-localid', '');
  2532. safeSetVal('ipsec-modal-remoteid', '');
  2533. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2534. // Phase 2 Fields
  2535. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2536. safeSetVal('ipsec-modal-espkeylife', '28800');
  2537. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2538. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2539. safeSetChecked('ipsec-modal-autostart', true);
  2540. safeSetChecked('ipsec-modal-disabled', false);
  2541. // Clear & Populate default dynamic subnets
  2542. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2543. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2544. if (localContainer) {
  2545. localContainer.innerHTML = '';
  2546. addIpsecLocalSubnet('192.168.10.0/24');
  2547. }
  2548. if (remoteContainer) {
  2549. remoteContainer.innerHTML = '';
  2550. addIpsecRemoteSubnet('192.168.20.0/24');
  2551. }
  2552. switchIpsecModalTab('p1');
  2553. modal.classList.remove('hidden');
  2554. }
  2555. function openEditIPSecModal(name) {
  2556. const modal = document.getElementById('ipsec-modal');
  2557. if (!modal) return;
  2558. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2559. if (!conn) return;
  2560. const title = document.getElementById('ipsec-modal-title');
  2561. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2562. // Phase 1 Fields
  2563. safeSetVal('ipsec-modal-name', conn.name);
  2564. const nameEl = document.getElementById('ipsec-modal-name');
  2565. if (nameEl) nameEl.readOnly = true;
  2566. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2567. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2568. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2569. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2570. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2571. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2572. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2573. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2574. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2575. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2576. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2577. // Phase 2 Fields
  2578. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2579. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2580. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2581. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2582. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2583. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2584. // Populate dynamic subnets
  2585. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2586. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2587. if (localContainer) {
  2588. localContainer.innerHTML = '';
  2589. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2590. locals.forEach(s => addIpsecLocalSubnet(s));
  2591. }
  2592. if (remoteContainer) {
  2593. remoteContainer.innerHTML = '';
  2594. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2595. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2596. }
  2597. switchIpsecModalTab('p1');
  2598. modal.classList.remove('hidden');
  2599. }
  2600. function closeAddIPSecModal() {
  2601. const modal = document.getElementById('ipsec-modal');
  2602. if (modal) modal.classList.add('hidden');
  2603. }
  2604. async function submitSaveIPSec(e) {
  2605. if (e) e.preventDefault();
  2606. const name = safeGetVal('ipsec-modal-name').trim();
  2607. if (!name) {
  2608. showToast('Error', 'Tunnel name is required', 'error');
  2609. return;
  2610. }
  2611. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2612. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2613. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2614. const comments = safeGetVal('ipsec-modal-comments').trim();
  2615. const psk = safeGetVal('ipsec-modal-psk');
  2616. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2617. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2618. const localId = safeGetVal('ipsec-modal-localid').trim();
  2619. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2620. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2621. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2622. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2623. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2624. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2625. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2626. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2627. // Scrape dynamic local and remote subnets
  2628. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2629. const localSubnets = [];
  2630. localInputs.forEach(inp => {
  2631. const v = inp.value.trim();
  2632. if (v) localSubnets.push(v);
  2633. });
  2634. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2635. const remoteSubnets = [];
  2636. remoteInputs.forEach(inp => {
  2637. const v = inp.value.trim();
  2638. if (v) remoteSubnets.push(v);
  2639. });
  2640. try {
  2641. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2642. method: 'POST',
  2643. headers: { 'Content-Type': 'application/json' },
  2644. body: JSON.stringify({
  2645. name,
  2646. comment: comments,
  2647. ike_version: ikeVersion,
  2648. local_addrs: localAddrs,
  2649. remote_addrs: remotegw,
  2650. preshared_key: psk,
  2651. ike_proposals: ikeProposals,
  2652. ike_keylife: ikeKeylife,
  2653. local_id: localId,
  2654. remote_id: remoteId,
  2655. dpd: dpd,
  2656. phase2_name: phase2Name,
  2657. esp_proposals: espProposals,
  2658. esp_keylife: espKeylife,
  2659. pfs_group: pfsGroup,
  2660. pfs: pfsGroup !== 'none',
  2661. local_subnets: localSubnets,
  2662. remote_subnets: remoteSubnets,
  2663. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2664. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2665. auto_start: autostart,
  2666. disabled
  2667. })
  2668. });
  2669. if (res.ok) {
  2670. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2671. closeAddIPSecModal();
  2672. loadIPSec(false);
  2673. } else {
  2674. const err = await res.json();
  2675. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2676. }
  2677. } catch (err) {
  2678. showToast('Error', err.message, 'error');
  2679. }
  2680. }
  2681. async function startIPSecTunnel(name) {
  2682. try {
  2683. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2684. if (res.ok) {
  2685. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2686. setTimeout(() => loadIPSec(false), 2000);
  2687. }
  2688. } catch (err) {
  2689. showToast('Error', err.message, 'error');
  2690. }
  2691. }
  2692. async function stopIPSecTunnel(name) {
  2693. try {
  2694. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2695. if (res.ok) {
  2696. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2697. loadIPSec(false);
  2698. }
  2699. } catch (err) {
  2700. showToast('Error', err.message, 'error');
  2701. }
  2702. }
  2703. async function toggleIPSecState(name, enable) {
  2704. try {
  2705. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2706. method: 'POST',
  2707. headers: { 'Content-Type': 'application/json' },
  2708. body: JSON.stringify({ enabled: enable })
  2709. });
  2710. if (res.ok) {
  2711. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2712. loadIPSec(false);
  2713. }
  2714. } catch (err) {
  2715. showToast('Error', err.message, 'error');
  2716. }
  2717. }
  2718. async function deleteIPSecConn(name) {
  2719. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2720. try {
  2721. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2722. if (res.ok) {
  2723. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2724. loadIPSec(false);
  2725. fetchData(false);
  2726. }
  2727. } catch (err) {
  2728. showToast('Error', err.message, 'error');
  2729. }
  2730. }
  2731. // ======================== L2TP Multi-Instance ========================
  2732. async function loadL2TP(populateInputs = true) {
  2733. try {
  2734. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2735. await fetchPPPProfilesList();
  2736. }
  2737. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2738. const list = await res.json();
  2739. state.l2tpList = Array.isArray(list) ? list : [];
  2740. const badge = document.getElementById('l2tp-count-badge');
  2741. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2742. const tbody = document.getElementById('l2tp-table-body');
  2743. const empty = document.getElementById('l2tp-empty');
  2744. if (!tbody) return;
  2745. tbody.innerHTML = '';
  2746. if (state.l2tpList.length === 0) {
  2747. if (empty) empty.classList.remove('hidden');
  2748. } else {
  2749. if (empty) empty.classList.add('hidden');
  2750. state.l2tpList.forEach(inst => {
  2751. const tr = document.createElement('tr');
  2752. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2753. tr.innerHTML = `
  2754. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2755. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2756. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2757. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2758. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2759. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2760. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2761. <td class="py-2.5 px-3 text-center">
  2762. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2763. ${inst.default_route ? 'Yes' : 'No'}
  2764. </span>
  2765. </td>
  2766. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2767. ${inst.running ? `
  2768. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2769. ` : `
  2770. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2771. `}
  2772. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2773. ${inst.disabled ? 'Enable' : 'Disable'}
  2774. </button>
  2775. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2776. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2777. </td>
  2778. `;
  2779. tbody.appendChild(tr);
  2780. });
  2781. }
  2782. } catch (err) {
  2783. console.error('Failed to load L2TP:', err);
  2784. }
  2785. }
  2786. async function openAddL2TPModal() {
  2787. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2788. await fetchPPPProfilesList();
  2789. }
  2790. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2791. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2792. document.getElementById('l2tp-modal-name').readOnly = false;
  2793. document.getElementById('l2tp-modal-server').value = '';
  2794. document.getElementById('l2tp-modal-user').value = '';
  2795. document.getElementById('l2tp-modal-pass').value = '';
  2796. document.getElementById('l2tp-modal-ipsec').value = '';
  2797. document.getElementById('l2tp-modal-defroute').checked = true;
  2798. document.getElementById('l2tp-modal-disabled').checked = false;
  2799. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2800. document.getElementById('l2tp-modal').classList.remove('hidden');
  2801. }
  2802. async function openEditL2TPModal(name) {
  2803. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2804. await fetchPPPProfilesList();
  2805. }
  2806. const inst = (state.l2tpList || []).find(i => i.name === name);
  2807. if (!inst) return;
  2808. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2809. document.getElementById('l2tp-modal-name').value = inst.name;
  2810. document.getElementById('l2tp-modal-name').readOnly = true;
  2811. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2812. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2813. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2814. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2815. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2816. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2817. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2818. document.getElementById('l2tp-modal').classList.remove('hidden');
  2819. }
  2820. function closeL2TPModal() {
  2821. document.getElementById('l2tp-modal').classList.add('hidden');
  2822. }
  2823. async function submitSaveL2TP(e) {
  2824. e.preventDefault();
  2825. const name = document.getElementById('l2tp-modal-name').value.trim();
  2826. const server = document.getElementById('l2tp-modal-server').value.trim();
  2827. const user = document.getElementById('l2tp-modal-user').value.trim();
  2828. const pass = document.getElementById('l2tp-modal-pass').value;
  2829. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2830. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2831. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2832. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2833. try {
  2834. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2835. method: 'POST',
  2836. headers: { 'Content-Type': 'application/json' },
  2837. body: JSON.stringify({
  2838. name,
  2839. connect_to: server,
  2840. username: user,
  2841. password: pass,
  2842. profile: profile,
  2843. ipsec_secret: ipsec,
  2844. default_route: defRoute,
  2845. disabled
  2846. })
  2847. });
  2848. if (res.ok) {
  2849. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2850. closeL2TPModal();
  2851. loadL2TP(false);
  2852. fetchData(false);
  2853. }
  2854. } catch (err) {
  2855. showToast('Error', err.message, 'error');
  2856. }
  2857. }
  2858. async function connectL2TPInstance(name) {
  2859. try {
  2860. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2861. if (res.ok) {
  2862. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2863. setTimeout(() => loadL2TP(false), 2000);
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function disconnectL2TPInstance(name) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2872. if (res.ok) {
  2873. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2874. loadL2TP(false);
  2875. }
  2876. } catch (err) {
  2877. showToast('Error', err.message, 'error');
  2878. }
  2879. }
  2880. async function toggleL2TPState(name, enable) {
  2881. try {
  2882. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2883. method: 'POST',
  2884. headers: { 'Content-Type': 'application/json' },
  2885. body: JSON.stringify({ enabled: enable })
  2886. });
  2887. if (res.ok) {
  2888. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2889. loadL2TP(false);
  2890. }
  2891. } catch (err) {
  2892. showToast('Error', err.message, 'error');
  2893. }
  2894. }
  2895. async function deleteL2TPInstance(name) {
  2896. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2897. try {
  2898. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2899. if (res.ok) {
  2900. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2901. loadL2TP(false);
  2902. fetchData(false);
  2903. }
  2904. } catch (err) {
  2905. showToast('Error', err.message, 'error');
  2906. }
  2907. }
  2908. // ======================== PPTP Multi-Instance ========================
  2909. async function loadPPTP(populateInputs = true) {
  2910. try {
  2911. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2912. await fetchPPPProfilesList();
  2913. }
  2914. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2915. const list = await res.json();
  2916. state.pptpList = Array.isArray(list) ? list : [];
  2917. const badge = document.getElementById('pptp-count-badge');
  2918. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2919. const tbody = document.getElementById('pptp-table-body');
  2920. const empty = document.getElementById('pptp-empty');
  2921. if (!tbody) return;
  2922. tbody.innerHTML = '';
  2923. if (state.pptpList.length === 0) {
  2924. if (empty) empty.classList.remove('hidden');
  2925. } else {
  2926. if (empty) empty.classList.add('hidden');
  2927. state.pptpList.forEach(inst => {
  2928. const tr = document.createElement('tr');
  2929. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2930. tr.innerHTML = `
  2931. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2932. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2933. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2934. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2935. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2936. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2937. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2938. <td class="py-2.5 px-3 text-center">
  2939. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2940. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2941. </span>
  2942. </td>
  2943. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2944. ${inst.running ? `
  2945. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2946. ` : `
  2947. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2948. `}
  2949. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2950. ${inst.disabled ? 'Enable' : 'Disable'}
  2951. </button>
  2952. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2953. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2954. </td>
  2955. `;
  2956. tbody.appendChild(tr);
  2957. });
  2958. }
  2959. } catch (err) {
  2960. console.error('Failed to load PPTP:', err);
  2961. }
  2962. }
  2963. async function openAddPPTPModal() {
  2964. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2965. await fetchPPPProfilesList();
  2966. }
  2967. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2968. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2969. document.getElementById('pptp-modal-name').readOnly = false;
  2970. document.getElementById('pptp-modal-server').value = '';
  2971. document.getElementById('pptp-modal-user').value = '';
  2972. document.getElementById('pptp-modal-pass').value = '';
  2973. document.getElementById('pptp-modal-mppe').checked = true;
  2974. document.getElementById('pptp-modal-defroute').checked = true;
  2975. document.getElementById('pptp-modal-disabled').checked = false;
  2976. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2977. document.getElementById('pptp-modal').classList.remove('hidden');
  2978. }
  2979. async function openEditPPTPModal(name) {
  2980. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2981. await fetchPPPProfilesList();
  2982. }
  2983. const inst = (state.pptpList || []).find(i => i.name === name);
  2984. if (!inst) return;
  2985. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2986. document.getElementById('pptp-modal-name').value = inst.name;
  2987. document.getElementById('pptp-modal-name').readOnly = true;
  2988. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2989. document.getElementById('pptp-modal-user').value = inst.username || '';
  2990. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2991. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2992. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2993. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2994. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2995. document.getElementById('pptp-modal').classList.remove('hidden');
  2996. }
  2997. function closePPTPModal() {
  2998. document.getElementById('pptp-modal').classList.add('hidden');
  2999. }
  3000. async function submitSavePPTP(e) {
  3001. e.preventDefault();
  3002. const name = document.getElementById('pptp-modal-name').value.trim();
  3003. const server = document.getElementById('pptp-modal-server').value.trim();
  3004. const user = document.getElementById('pptp-modal-user').value.trim();
  3005. const pass = document.getElementById('pptp-modal-pass').value;
  3006. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  3007. const mppe = document.getElementById('pptp-modal-mppe').checked;
  3008. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  3009. const disabled = document.getElementById('pptp-modal-disabled').checked;
  3010. try {
  3011. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  3012. method: 'POST',
  3013. headers: { 'Content-Type': 'application/json' },
  3014. body: JSON.stringify({
  3015. name,
  3016. connect_to: server,
  3017. username: user,
  3018. password: pass,
  3019. profile: profile,
  3020. require_mppe: mppe,
  3021. default_route: defRoute,
  3022. auto_reconnect: true,
  3023. disabled
  3024. })
  3025. });
  3026. if (res.ok) {
  3027. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  3028. closePPTPModal();
  3029. loadPPTP(false);
  3030. fetchData(false);
  3031. }
  3032. } catch (err) {
  3033. showToast('Error', err.message, 'error');
  3034. }
  3035. }
  3036. async function connectPPTPInstance(name) {
  3037. try {
  3038. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3039. if (res.ok) {
  3040. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3041. setTimeout(() => loadPPTP(false), 2000);
  3042. }
  3043. } catch (err) {
  3044. showToast('Error', err.message, 'error');
  3045. }
  3046. }
  3047. async function disconnectPPTPInstance(name) {
  3048. try {
  3049. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3050. if (res.ok) {
  3051. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3052. loadPPTP(false);
  3053. }
  3054. } catch (err) {
  3055. showToast('Error', err.message, 'error');
  3056. }
  3057. }
  3058. async function togglePPTPState(name, enable) {
  3059. try {
  3060. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3061. method: 'POST',
  3062. headers: { 'Content-Type': 'application/json' },
  3063. body: JSON.stringify({ enabled: enable })
  3064. });
  3065. if (res.ok) {
  3066. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3067. loadPPTP(false);
  3068. }
  3069. } catch (err) {
  3070. showToast('Error', err.message, 'error');
  3071. }
  3072. }
  3073. async function deletePPTPInstance(name) {
  3074. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3075. try {
  3076. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3077. if (res.ok) {
  3078. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3079. loadPPTP(false);
  3080. fetchData(false);
  3081. }
  3082. } catch (err) {
  3083. showToast('Error', err.message, 'error');
  3084. }
  3085. }
  3086. // ---------------- Modal & Helper Functions ----------------
  3087. function openVlanModal(defaultParent = '') {
  3088. const select = document.getElementById('vlan-parent');
  3089. select.innerHTML = '';
  3090. const allIfaces = state.interfaces || [];
  3091. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3092. if (eligible.length === 0) {
  3093. const opt = document.createElement('option');
  3094. opt.value = '';
  3095. opt.innerText = 'No VLAN-capable interfaces available';
  3096. select.appendChild(opt);
  3097. } else {
  3098. eligible.forEach(i => {
  3099. const opt = document.createElement('option');
  3100. opt.value = i.name;
  3101. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3102. if (i.name === defaultParent) opt.selected = true;
  3103. select.appendChild(opt);
  3104. });
  3105. }
  3106. document.getElementById('vlan-id').value = '';
  3107. document.getElementById('vlan-name').value = '';
  3108. document.getElementById('vlan-ip').value = '';
  3109. document.getElementById('vlan-desc').value = '';
  3110. populateRoleSelects('LAN');
  3111. autoSuggestVlanName();
  3112. document.getElementById('vlan-modal').classList.remove('hidden');
  3113. }
  3114. function closeVlanModal() {
  3115. document.getElementById('vlan-modal').classList.add('hidden');
  3116. }
  3117. function autoSuggestVlanName() {
  3118. const parent = document.getElementById('vlan-parent').value;
  3119. if (!parent) return;
  3120. const id = document.getElementById('vlan-id').value;
  3121. const nameInput = document.getElementById('vlan-name');
  3122. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3123. }
  3124. function setSubnetPreset(cidr) {
  3125. const ipInput = document.getElementById('vlan-ip');
  3126. const id = document.getElementById('vlan-id').value || '10';
  3127. ipInput.value = `192.168.${id}.1${cidr}`;
  3128. }
  3129. async function submitCreateVlan(e) {
  3130. e.preventDefault();
  3131. const btn = document.getElementById('vlan-submit-btn');
  3132. btn.disabled = true;
  3133. btn.innerText = 'Creating...';
  3134. const parent = document.getElementById('vlan-parent').value;
  3135. if (!parent) {
  3136. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3137. btn.disabled = false;
  3138. btn.innerText = 'Create VLAN';
  3139. return;
  3140. }
  3141. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3142. const name = document.getElementById('vlan-name').value.trim();
  3143. const ip = document.getElementById('vlan-ip').value.trim();
  3144. const role = document.getElementById('vlan-role').value;
  3145. const desc = document.getElementById('vlan-desc').value.trim();
  3146. try {
  3147. const res = await fetch(`${API_BASE}/vlans`, {
  3148. method: 'POST',
  3149. headers: { 'Content-Type': 'application/json' },
  3150. body: JSON.stringify({
  3151. parent_name: parent,
  3152. vlan_id: id,
  3153. name: name,
  3154. ip_address: ip,
  3155. role: role,
  3156. description: desc,
  3157. mtu: 1500,
  3158. auto_up: true
  3159. })
  3160. });
  3161. const data = await res.json();
  3162. if (res.ok) {
  3163. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3164. state.expandedParents.add(parent);
  3165. closeVlanModal();
  3166. await fetchData(true);
  3167. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3168. } else {
  3169. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3170. }
  3171. } catch (err) {
  3172. showToast('Error', err.message, 'error');
  3173. } finally {
  3174. btn.disabled = false;
  3175. btn.innerText = 'Create VLAN';
  3176. }
  3177. }
  3178. async function confirmDeleteVlan(name) {
  3179. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3184. closeIfaceModal();
  3185. fetchData(true);
  3186. }
  3187. } catch (err) {
  3188. showToast('Error', err.message, 'error');
  3189. }
  3190. }
  3191. function openIfaceModal(name) {
  3192. const iface = (state.interfaces || []).find(i => i.name === name);
  3193. if (!iface) return;
  3194. state.currentModalIface = iface.name;
  3195. document.getElementById('modal-iface-name').innerText = iface.name;
  3196. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3197. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3198. populateRoleSelects(iface.role || 'LAN');
  3199. document.getElementById('modal-iface-desc').value = iface.description || '';
  3200. const nameInput = document.getElementById('modal-iface-new-name');
  3201. const renameBtn = document.getElementById('modal-btn-rename');
  3202. const renameHelp = document.getElementById('modal-iface-rename-help');
  3203. if (nameInput) {
  3204. nameInput.value = iface.name;
  3205. if (iface.name === 'lo' || iface.type === 'loopback') {
  3206. nameInput.disabled = true;
  3207. if (renameBtn) renameBtn.disabled = true;
  3208. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3209. } else {
  3210. nameInput.disabled = false;
  3211. if (renameBtn) renameBtn.disabled = false;
  3212. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3213. }
  3214. }
  3215. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3216. if (iface.is_vlan) {
  3217. delBtn.classList.remove('hidden');
  3218. } else {
  3219. delBtn.classList.add('hidden');
  3220. }
  3221. renderModalIPs(iface);
  3222. document.getElementById('iface-modal').classList.remove('hidden');
  3223. }
  3224. function renderModalIPs(iface) {
  3225. const container = document.getElementById('modal-ip-list');
  3226. container.innerHTML = '';
  3227. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3228. if (addrs.length === 0) {
  3229. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3230. return;
  3231. }
  3232. addrs.forEach(addr => {
  3233. const row = document.createElement('div');
  3234. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3235. row.innerHTML = `
  3236. <span class="text-white">${addr}</span>
  3237. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3238. `;
  3239. container.appendChild(row);
  3240. });
  3241. }
  3242. function closeIfaceModal() {
  3243. document.getElementById('iface-modal').classList.add('hidden');
  3244. state.currentModalIface = null;
  3245. }
  3246. async function setIfaceState(name, newState) {
  3247. const target = name || state.currentModalIface;
  3248. if (!target) return;
  3249. await toggleInterfaceState(target, newState);
  3250. const updated = (state.interfaces || []).find(i => i.name === target);
  3251. if (updated) openIfaceModal(target);
  3252. }
  3253. async function applyMTU() {
  3254. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3255. try {
  3256. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3257. method: 'POST',
  3258. headers: { 'Content-Type': 'application/json' },
  3259. body: JSON.stringify({ mtu })
  3260. });
  3261. if (res.ok) {
  3262. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3263. fetchData(false);
  3264. }
  3265. } catch (err) {
  3266. showToast('Error', err.message, 'error');
  3267. }
  3268. }
  3269. async function addInterfaceIP() {
  3270. const ip = document.getElementById('modal-new-ip').value.trim();
  3271. if (!ip) return;
  3272. try {
  3273. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3274. method: 'POST',
  3275. headers: { 'Content-Type': 'application/json' },
  3276. body: JSON.stringify({ ip })
  3277. });
  3278. if (res.ok) {
  3279. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3280. document.getElementById('modal-new-ip').value = '';
  3281. await fetchData(false);
  3282. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3283. if (iface) renderModalIPs(iface);
  3284. } else {
  3285. const err = await res.json();
  3286. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3287. }
  3288. } catch (err) {
  3289. showToast('Error', err.message, 'error');
  3290. }
  3291. }
  3292. async function removeInterfaceIP(ip) {
  3293. if (!confirm(`Remove IP ${ip}?`)) return;
  3294. try {
  3295. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3296. method: 'DELETE',
  3297. headers: { 'Content-Type': 'application/json' },
  3298. body: JSON.stringify({ ip })
  3299. });
  3300. if (res.ok) {
  3301. showToast('IP Removed', `Removed ${ip}`, 'success');
  3302. await fetchData(false);
  3303. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3304. if (iface) renderModalIPs(iface);
  3305. }
  3306. } catch (err) {
  3307. showToast('Error', err.message, 'error');
  3308. }
  3309. }
  3310. async function renameInterface() {
  3311. const oldName = state.currentModalIface;
  3312. const newNameInput = document.getElementById('modal-iface-new-name');
  3313. const newName = (newNameInput?.value || '').trim();
  3314. if (!oldName) return;
  3315. if (!newName) {
  3316. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3317. return;
  3318. }
  3319. if (newName === oldName) {
  3320. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3321. return;
  3322. }
  3323. if (newName.length > 15) {
  3324. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3325. return;
  3326. }
  3327. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3328. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3329. return;
  3330. }
  3331. const renameBtn = document.getElementById('modal-btn-rename');
  3332. if (renameBtn) {
  3333. renameBtn.disabled = true;
  3334. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3335. }
  3336. try {
  3337. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3338. method: 'POST',
  3339. headers: { 'Content-Type': 'application/json' },
  3340. body: JSON.stringify({ new_name: newName })
  3341. });
  3342. const data = await res.json();
  3343. if (!res.ok) {
  3344. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3345. return;
  3346. }
  3347. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3348. state.currentModalIface = newName;
  3349. document.getElementById('modal-iface-name').innerText = newName;
  3350. // Refresh application state
  3351. await fetchData(false);
  3352. const updated = (state.interfaces || []).find(i => i.name === newName);
  3353. if (updated) {
  3354. openIfaceModal(newName);
  3355. } else {
  3356. closeIfaceModal();
  3357. }
  3358. } catch (err) {
  3359. showToast('Error', err.message, 'error');
  3360. } finally {
  3361. if (renameBtn) {
  3362. renameBtn.disabled = false;
  3363. renameBtn.innerHTML = `
  3364. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3365. <span>Rename</span>
  3366. `;
  3367. }
  3368. }
  3369. }
  3370. async function saveInterfaceMetadata() {
  3371. const oldName = state.currentModalIface;
  3372. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3373. const role = document.getElementById('modal-iface-role').value;
  3374. const desc = document.getElementById('modal-iface-desc').value.trim();
  3375. let targetName = oldName;
  3376. // If user changed the name before clicking Save Changes, execute rename first
  3377. if (newName && newName !== oldName && oldName !== 'lo') {
  3378. try {
  3379. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3380. method: 'POST',
  3381. headers: { 'Content-Type': 'application/json' },
  3382. body: JSON.stringify({ new_name: newName })
  3383. });
  3384. const data = await renameRes.json();
  3385. if (!renameRes.ok) {
  3386. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3387. return;
  3388. }
  3389. targetName = newName;
  3390. state.currentModalIface = newName;
  3391. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3392. } catch (err) {
  3393. showToast('Error', err.message, 'error');
  3394. return;
  3395. }
  3396. }
  3397. try {
  3398. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3399. method: 'POST',
  3400. headers: { 'Content-Type': 'application/json' },
  3401. body: JSON.stringify({ role, description: desc })
  3402. });
  3403. if (res.ok) {
  3404. showToast('Saved', 'Interface configuration updated', 'success');
  3405. closeIfaceModal();
  3406. fetchData(false);
  3407. } else {
  3408. const err = await res.json();
  3409. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3410. }
  3411. } catch (err) {
  3412. showToast('Error', err.message, 'error');
  3413. }
  3414. }
  3415. // ======================== IPTABLES FIREWALL ========================
  3416. state.fwSubTab = 'filter';
  3417. state.routesSubTab = 'routes';
  3418. function nativeNATChain(chain) {
  3419. const value = (chain || '').toLowerCase();
  3420. if (value === 'dstnat') return 'prerouting';
  3421. if (value === 'srcnat') return 'postrouting';
  3422. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3423. }
  3424. function nativeFirewallTarget(action) {
  3425. const name = (action || '').toLowerCase();
  3426. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3427. }
  3428. function renderRuleFlag(disabled, hasComment) {
  3429. let flags = '';
  3430. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3431. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3432. return flags || '<span class="text-slate-600">-</span>';
  3433. }
  3434. function renderActionBadge(action) {
  3435. const act = (action || '').toLowerCase();
  3436. let color = 'bg-slate-800 text-slate-300';
  3437. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3438. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3439. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3440. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3441. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3442. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3443. }
  3444. function switchFWSubTab(tab) {
  3445. state.fwSubTab = tab;
  3446. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3447. tabs.forEach(t => {
  3448. const panel = document.getElementById(`fw-subtab-${t}`);
  3449. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3450. if (panel) {
  3451. if (t === tab) panel.classList.remove('hidden');
  3452. else panel.classList.add('hidden');
  3453. }
  3454. if (btn) {
  3455. if (t === tab) {
  3456. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3457. } else {
  3458. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3459. }
  3460. }
  3461. });
  3462. const addBtn = document.getElementById('fw-primary-add-btn');
  3463. if (addBtn) {
  3464. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3465. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3466. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3467. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3468. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3469. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3470. }
  3471. if (tab === 'filter') renderFilterRules();
  3472. else if (tab === 'nat') renderNATRules();
  3473. else if (tab === 'mangle') renderMangleRules();
  3474. else if (tab === 'addrlist') renderAddressLists();
  3475. else if (tab === 'geo') loadGeoIP();
  3476. else if (tab === 'connections') loadConnections();
  3477. setTimeout(initTableSorting, 50);
  3478. }
  3479. function openCurrentFWModal() {
  3480. if (state.fwSubTab === 'filter') openAddFilterModal();
  3481. else if (state.fwSubTab === 'nat') openAddNATModal();
  3482. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3483. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3484. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3485. else if (state.fwSubTab === 'connections') loadConnections();
  3486. }
  3487. async function loadFirewall(populateDropdowns = true) {
  3488. try {
  3489. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3490. fetch(`${API_BASE}/firewall/summary`),
  3491. fetch(`${API_BASE}/firewall/filter`),
  3492. fetch(`${API_BASE}/firewall/nat`),
  3493. fetch(`${API_BASE}/firewall/mangle`),
  3494. fetch(`${API_BASE}/firewall/address-lists`),
  3495. fetch(`${API_BASE}/firewall/geoip/status`),
  3496. fetch(`${API_BASE}/firewall/geoip/countries`)
  3497. ]);
  3498. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3499. const applyError = document.getElementById('fw-apply-error');
  3500. if (applyError) {
  3501. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3502. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3503. }
  3504. if (filterRes.ok) state.filterRules = await filterRes.json();
  3505. if (natRes.ok) state.natRules = await natRes.json();
  3506. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3507. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3508. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3509. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3510. if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
  3511. // Badges
  3512. const bFilter = document.getElementById('fw-badge-filter');
  3513. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3514. const bNat = document.getElementById('fw-badge-nat');
  3515. if (bNat) bNat.innerText = (state.natRules || []).length;
  3516. const bMangle = document.getElementById('fw-badge-mangle');
  3517. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3518. const bAddr = document.getElementById('fw-badge-addrlist');
  3519. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3520. const bGeo = document.getElementById('fw-badge-geo');
  3521. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3522. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3523. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3524. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3525. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3526. const tbodyFilter = document.getElementById('filter-table-body');
  3527. if (tbodyFilter) {
  3528. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3529. tbodyFilter.dataset.sig = sigFilter;
  3530. renderFilterRules();
  3531. } else {
  3532. // In-place live stats update (ZERO flicker)
  3533. (state.filterRules || []).forEach(r => {
  3534. const p = document.getElementById(`filter-pkts-${r.id}`);
  3535. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3536. const b = document.getElementById(`filter-bytes-${r.id}`);
  3537. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3538. });
  3539. }
  3540. }
  3541. const tbodyNat = document.getElementById('nat-table-body');
  3542. if (tbodyNat) {
  3543. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3544. tbodyNat.dataset.sig = sigNat;
  3545. renderNATRules();
  3546. } else {
  3547. (state.natRules || []).forEach(r => {
  3548. const p = document.getElementById(`nat-pkts-${r.id}`);
  3549. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3550. const b = document.getElementById(`nat-bytes-${r.id}`);
  3551. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3552. });
  3553. }
  3554. }
  3555. const tbodyMangle = document.getElementById('mangle-table-body');
  3556. if (tbodyMangle) {
  3557. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3558. tbodyMangle.dataset.sig = sigMangle;
  3559. renderMangleRules();
  3560. } else {
  3561. (state.mangleRules || []).forEach(r => {
  3562. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3563. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3564. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3565. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3566. });
  3567. }
  3568. }
  3569. const tbodyAddr = document.getElementById('addrlist-table-body');
  3570. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3571. tbodyAddr.dataset.sig = sigAddr;
  3572. renderAddressLists();
  3573. }
  3574. renderGeoCountries();
  3575. if (state.fwSubTab === 'connections') {
  3576. loadConnections();
  3577. }
  3578. } catch (err) {
  3579. console.error('Failed to load firewall:', err);
  3580. }
  3581. }
  3582. // ----------------- Filter Rules -----------------
  3583. function renderFilterRules() {
  3584. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3585. const tbody = document.getElementById('filter-table-body');
  3586. const empty = document.getElementById('filter-empty');
  3587. if (!tbody) return;
  3588. tbody.innerHTML = '';
  3589. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3590. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3591. if (rules.length === 0) {
  3592. empty?.classList.remove('hidden');
  3593. return;
  3594. }
  3595. empty?.classList.add('hidden');
  3596. rules.forEach((raw, idx) => {
  3597. const r = safeFirewallRow(raw);
  3598. const tr = document.createElement('tr');
  3599. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3600. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3601. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3602. let actionExtra = '';
  3603. if (r.action === 'reject') {
  3604. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3605. } else if (r.action === 'jump') {
  3606. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3607. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3608. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3609. } else if (r.action === 'log' && r.log_prefix) {
  3610. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3611. }
  3612. tr.innerHTML = `
  3613. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3614. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3615. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3616. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3617. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3618. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  3619. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3620. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3621. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3622. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3623. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3624. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3625. </td>
  3626. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3627. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3628. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3629. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3630. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3631. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3632. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3633. </td>
  3634. `;
  3635. tbody.appendChild(tr);
  3636. });
  3637. }
  3638. function formatTarget(addr, list, geo) {
  3639. const parts = [];
  3640. if (addr) parts.push(`<span>${addr}</span>`);
  3641. if (list) {
  3642. const inv = list.startsWith('!') ? '!' : '';
  3643. const clean = list.replace(/^!/, '');
  3644. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  3645. }
  3646. if (geo) {
  3647. const inv = geo.startsWith('!') ? '!' : '';
  3648. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3649. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  3650. }
  3651. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3652. return parts.join(' ');
  3653. }
  3654. function populateInterfaceSelect(selectId, currentVal = '') {
  3655. const sel = document.getElementById(selectId);
  3656. if (!sel) return;
  3657. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3658. (state.interfaces || []).forEach(i => {
  3659. const opt = document.createElement('option');
  3660. opt.value = i.name;
  3661. opt.innerText = `${i.name} (${i.role || i.type})`;
  3662. if (i.name === currentVal) opt.selected = true;
  3663. sel.appendChild(opt);
  3664. });
  3665. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3666. const optgroup = document.createElement('optgroup');
  3667. optgroup.label = 'SD-WAN Groups';
  3668. state.sdwanGroups.forEach(g => {
  3669. const opt = document.createElement('option');
  3670. opt.value = g.name;
  3671. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3672. if (g.name === currentVal) opt.selected = true;
  3673. optgroup.appendChild(opt);
  3674. });
  3675. sel.appendChild(optgroup);
  3676. }
  3677. }
  3678. function populateAddressListSelect(selectId, currentVal = '') {
  3679. const sel = document.getElementById(selectId);
  3680. if (!sel) return;
  3681. sel.innerHTML = '<option value="">(None)</option>';
  3682. const cleanVal = (currentVal || '').replace(/^!/, '');
  3683. const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
  3684. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3685. customNames.forEach(name => {
  3686. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3687. const opt = document.createElement('option');
  3688. opt.value = name;
  3689. opt.innerText = `${name} (${count} entries)`;
  3690. if (name === cleanVal) opt.selected = true;
  3691. sel.appendChild(opt);
  3692. });
  3693. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3694. const opt = document.createElement('option');
  3695. opt.value = cleanVal;
  3696. opt.innerText = cleanVal;
  3697. opt.selected = true;
  3698. sel.appendChild(opt);
  3699. }
  3700. populateCommonAddrListDatalist();
  3701. }
  3702. function populateCommonAddrListDatalist() {
  3703. const dl = document.getElementById('fw-addrlist-datalist');
  3704. if (!dl) return;
  3705. dl.innerHTML = '';
  3706. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3707. names.forEach(name => {
  3708. const opt = document.createElement('option');
  3709. opt.value = name;
  3710. dl.appendChild(opt);
  3711. });
  3712. }
  3713. function populateGeoIPSelect(selectId, currentVal = '') {
  3714. const sel = document.getElementById(selectId);
  3715. if (!sel) return;
  3716. sel.innerHTML = '<option value="">(None)</option>';
  3717. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3718. // Presets optgroup
  3719. const grpPresets = document.createElement('optgroup');
  3720. grpPresets.label = '⚡ Regional Presets';
  3721. const presets = [
  3722. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3723. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3724. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3725. ];
  3726. presets.forEach(p => {
  3727. const opt = document.createElement('option');
  3728. opt.value = p.code;
  3729. opt.innerText = p.label;
  3730. if (p.code === cleanVal) opt.selected = true;
  3731. grpPresets.appendChild(opt);
  3732. });
  3733. sel.appendChild(grpPresets);
  3734. // All Countries optgroup
  3735. const grpCountries = document.createElement('optgroup');
  3736. grpCountries.label = '🌍 All Countries';
  3737. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3738. countries.forEach(c => {
  3739. const opt = document.createElement('option');
  3740. opt.value = c.code;
  3741. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3742. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3743. if (c.code === cleanVal) opt.selected = true;
  3744. grpCountries.appendChild(opt);
  3745. });
  3746. sel.appendChild(grpCountries);
  3747. }
  3748. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3749. function switchFwRuleTab(tab) {
  3750. state.activeFwRuleTab = tab;
  3751. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3752. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3753. btn.classList.add('text-slate-400', 'border-transparent');
  3754. });
  3755. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3756. if (activeBtn) {
  3757. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3758. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3759. }
  3760. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3761. const activePane = document.getElementById(`fw-pane-${tab}`);
  3762. if (activePane) activePane.classList.remove('hidden');
  3763. if (tab === 'statistics') {
  3764. startFwStatPolling();
  3765. } else {
  3766. stopFwStatPolling();
  3767. }
  3768. }
  3769. function toggleFwField(fieldKey, expand) {
  3770. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3771. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3772. if (!plusBtn || !fieldBox) return;
  3773. if (expand) {
  3774. plusBtn.classList.add('hidden');
  3775. fieldBox.classList.remove('hidden');
  3776. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3777. if (valInput) valInput.focus();
  3778. } else {
  3779. fieldBox.classList.add('hidden');
  3780. plusBtn.classList.remove('hidden');
  3781. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3782. if (valInput) {
  3783. if (valInput.tagName === 'SELECT') {
  3784. valInput.selectedIndex = 0;
  3785. } else {
  3786. valInput.value = '';
  3787. }
  3788. }
  3789. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3790. if (invInput) invInput.checked = false;
  3791. if (fieldKey === 'cs') {
  3792. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3793. const el = document.getElementById(id);
  3794. if (el) el.checked = false;
  3795. });
  3796. }
  3797. if (fieldKey === 'natstate') {
  3798. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3799. const el = document.getElementById(id);
  3800. if (el) el.checked = false;
  3801. });
  3802. }
  3803. if (fieldKey === 'days') {
  3804. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3805. const el = document.getElementById(`fw-day-${d}`);
  3806. if (el) el.checked = true;
  3807. });
  3808. }
  3809. }
  3810. }
  3811. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3812. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3813. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3814. toggleFwField(fieldKey, true);
  3815. let strVal = String(value);
  3816. if (hasInvert) {
  3817. const inv = strVal.startsWith('!');
  3818. if (inv) strVal = strVal.slice(1);
  3819. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3820. if (invEl) invEl.checked = inv;
  3821. else if (inv) strVal = '!'+strVal;
  3822. }
  3823. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3824. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  3825. } else {
  3826. toggleFwField(fieldKey, false);
  3827. }
  3828. }
  3829. function getFwFieldVal(fieldKey, hasInvert = false) {
  3830. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3831. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3832. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3833. let v = valEl ? valEl.value.trim() : '';
  3834. if (!v) return '';
  3835. if (hasInvert) {
  3836. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3837. if (invEl && invEl.checked) {
  3838. v = '!' + v.replace(/^!/, '');
  3839. }
  3840. }
  3841. return v;
  3842. }
  3843. function toggleMaximizeFilterModal() {
  3844. const win = document.getElementById('filter-modal-window');
  3845. if (!win) return;
  3846. if (win.classList.contains('max-w-[720px]')) {
  3847. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3848. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3849. } else {
  3850. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3851. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3852. }
  3853. }
  3854. const FW_NATIVE_CHAINS = {
  3855. filter: [
  3856. { id: 'forward', label: 'FORWARD (routed through router)' },
  3857. { id: 'input', label: 'INPUT (destined to this router)' },
  3858. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3859. ],
  3860. nat: [
  3861. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3862. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3863. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3864. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3865. ],
  3866. mangle: [
  3867. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3868. { id: 'input', label: 'INPUT (destined to this machine)' },
  3869. { id: 'forward', label: 'FORWARD (routed through router)' },
  3870. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3871. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3872. ]
  3873. };
  3874. function populateChainDropdown(table, currentChain) {
  3875. const sel = document.getElementById(`${table}-modal-chain-select`);
  3876. if (!sel) return;
  3877. const cur = (currentChain || '').trim();
  3878. const lower = cur.toLowerCase();
  3879. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3880. const rules = state[rulesKey] || [];
  3881. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3882. const customChains = new Set();
  3883. rules.forEach(r => {
  3884. if (r.chain) {
  3885. const c = r.chain.trim();
  3886. const l = c.toLowerCase();
  3887. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3888. customChains.add(c);
  3889. }
  3890. }
  3891. });
  3892. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3893. if (isCurrentCustom) {
  3894. customChains.add(cur);
  3895. }
  3896. let html = '';
  3897. FW_NATIVE_CHAINS[table].forEach(c => {
  3898. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3899. });
  3900. if (customChains.size > 0) {
  3901. html += `<optgroup label="Custom Chains">`;
  3902. customChains.forEach(c => {
  3903. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3904. });
  3905. html += `</optgroup>`;
  3906. }
  3907. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3908. sel.innerHTML = html;
  3909. if (isCurrentCustom) {
  3910. sel.value = cur;
  3911. } else if (nativeIds.includes(lower)) {
  3912. sel.value = lower;
  3913. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3914. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3915. } else {
  3916. sel.value = nativeIds[0];
  3917. }
  3918. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3919. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3920. if (isCurrentCustom || sel.value === '__custom__') {
  3921. if (customWrap) customWrap.classList.remove('hidden');
  3922. if (customInput) customInput.value = cur;
  3923. } else {
  3924. if (customWrap) customWrap.classList.add('hidden');
  3925. if (customInput) customInput.value = '';
  3926. }
  3927. const chainInput = document.getElementById(`${table}-modal-chain`);
  3928. if (chainInput) chainInput.value = cur || sel.value;
  3929. }
  3930. function syncFilterChainFromSelect() {
  3931. const sel = document.getElementById('filter-modal-chain-select');
  3932. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3933. const customInput = document.getElementById('filter-modal-custom-input');
  3934. const chainInput = document.getElementById('filter-modal-chain');
  3935. if (!sel || !chainInput) return;
  3936. if (sel.value === '__custom__') {
  3937. if (customWrap) customWrap.classList.remove('hidden');
  3938. if (customInput) {
  3939. customInput.value = '';
  3940. customInput.focus();
  3941. }
  3942. chainInput.value = '';
  3943. } else {
  3944. if (customWrap) customWrap.classList.add('hidden');
  3945. chainInput.value = sel.value;
  3946. }
  3947. handleFilterChainChange();
  3948. }
  3949. function syncFilterCustomChainInput() {
  3950. const customInput = document.getElementById('filter-modal-custom-input');
  3951. const chainInput = document.getElementById('filter-modal-chain');
  3952. if (customInput && chainInput) {
  3953. chainInput.value = customInput.value.trim();
  3954. }
  3955. handleFilterChainChange();
  3956. }
  3957. function handleFilterChainChange() {
  3958. const chainInput = document.getElementById('filter-modal-chain');
  3959. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3960. const sel = document.getElementById('filter-modal-chain-select');
  3961. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3962. if (['forward', 'input', 'output'].includes(chain)) {
  3963. sel.value = chain;
  3964. }
  3965. }
  3966. const hintEl = document.getElementById('filter-chain-hint');
  3967. if (hintEl) {
  3968. if (chain === 'forward') {
  3969. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3970. } else if (chain === 'input') {
  3971. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3972. } else if (chain === 'output') {
  3973. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3974. } else {
  3975. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3976. }
  3977. }
  3978. const rowIn = document.getElementById('fw-row-iniface');
  3979. const rowInList = document.getElementById('fw-row-inifacelist');
  3980. const rowOut = document.getElementById('fw-row-outiface');
  3981. const rowOutList = document.getElementById('fw-row-outifacelist');
  3982. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3983. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3984. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3985. if (chain === 'input') {
  3986. if (rowIn) rowIn.classList.remove('hidden');
  3987. if (rowInList) rowInList.classList.remove('hidden');
  3988. if (rowOut) rowOut.classList.add('hidden');
  3989. if (rowOutList) rowOutList.classList.add('hidden');
  3990. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3991. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  3992. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3993. } else if (chain === 'output') {
  3994. if (rowIn) rowIn.classList.add('hidden');
  3995. if (rowInList) rowInList.classList.add('hidden');
  3996. if (rowOut) rowOut.classList.remove('hidden');
  3997. if (rowOutList) rowOutList.classList.remove('hidden');
  3998. if (rowInBridge) rowInBridge.classList.add('hidden');
  3999. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4000. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4001. } else {
  4002. if (rowIn) rowIn.classList.remove('hidden');
  4003. if (rowInList) rowInList.classList.remove('hidden');
  4004. if (rowOut) rowOut.classList.remove('hidden');
  4005. if (rowOutList) rowOutList.classList.remove('hidden');
  4006. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4007. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4008. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4009. }
  4010. checkFilterActionChainCompatibility();
  4011. }
  4012. function checkFilterActionChainCompatibility() {
  4013. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4014. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4015. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4016. if (!warnBox || !warnMsg) return;
  4017. if (chain === 'prerouting' || chain === 'postrouting') {
  4018. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4019. warnBox.classList.remove('hidden');
  4020. } else {
  4021. warnBox.classList.add('hidden');
  4022. }
  4023. }
  4024. function openAddFilterModal() {
  4025. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4026. switchFwRuleTab('general');
  4027. setFirewallDays('fw', '');
  4028. const badge = document.getElementById('fw-modal-badge');
  4029. if (badge) badge.innerText = 'New...';
  4030. document.getElementById('filter-modal-id').value = '';
  4031. document.getElementById('filter-modal-family').value = '4';
  4032. document.getElementById('filter-modal-enabled').checked = true;
  4033. document.getElementById('filter-modal-comment').value = '';
  4034. document.getElementById('filter-modal-chain').value = 'forward';
  4035. populateChainDropdown('filter', 'forward');
  4036. handleFilterChainChange();
  4037. document.getElementById('filter-modal-action').value = 'accept';
  4038. document.getElementById('filter-modal-log').checked = false;
  4039. populateInterfaceSelect('fw-val-iniface');
  4040. populateInterfaceSelect('fw-val-outiface');
  4041. populateAddressListSelect('fw-val-srclist');
  4042. populateAddressListSelect('fw-val-dstlist');
  4043. populateGeoIPSelect('fw-val-srcgeo');
  4044. populateGeoIPSelect('fw-val-dstgeo');
  4045. const allFieldKeys = [
  4046. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4047. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4048. 'routingmark', 'conntype', 'cs', 'natstate',
  4049. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4050. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4051. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4052. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4053. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4054. ];
  4055. allFieldKeys.forEach(k => toggleFwField(k, false));
  4056. resetRuleCounterDisplay();
  4057. toggleFilterActionFields();
  4058. refreshFirewallRejectTypes();
  4059. document.getElementById('filter-modal').classList.remove('hidden');
  4060. }
  4061. function openEditFilterModal(id) {
  4062. id = decodeURIComponent(id);
  4063. const r = (state.filterRules || []).find(rule => rule.id === id);
  4064. if (!r) return;
  4065. switchFwRuleTab('general');
  4066. const badge = document.getElementById('fw-modal-badge');
  4067. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4068. document.getElementById('filter-modal-id').value = r.id;
  4069. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4070. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4071. document.getElementById('filter-modal-comment').value = r.comment || '';
  4072. const filterChain = r.chain || 'forward';
  4073. document.getElementById('filter-modal-chain').value = filterChain;
  4074. populateChainDropdown('filter', filterChain);
  4075. handleFilterChainChange();
  4076. setFirewallActionSelection('filter', r.action || 'accept');
  4077. document.getElementById('filter-modal-log').checked = !!r.log;
  4078. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4079. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4080. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4081. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4082. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4083. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4084. setFwFieldVal('src', r.src_address, true);
  4085. setFwFieldVal('dst', r.dst_address, true);
  4086. setFwFieldVal('srclist', r.src_address_list, true);
  4087. setFwFieldVal('dstlist', r.dst_address_list, true);
  4088. setFwFieldVal('srcgeo', r.src_geoip, true);
  4089. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4090. if (r.protocol && r.protocol !== 'all') {
  4091. setFwFieldVal('proto', r.protocol, true);
  4092. } else {
  4093. toggleFwField('proto', false);
  4094. }
  4095. setFwFieldVal('sport', r.src_port, true);
  4096. setFwFieldVal('dport', r.dst_port, true);
  4097. setFwFieldVal('anyport', r.any_port, true);
  4098. setFwFieldVal('iniface', r.in_interface, true);
  4099. setFwFieldVal('outiface', r.out_interface, true);
  4100. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4101. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4102. setFwFieldVal('pktmark', r.packet_mark, true);
  4103. setFwFieldVal('connmark', r.connection_mark, true);
  4104. setFwFieldVal('routingmark', r.routing_mark, true);
  4105. setFwFieldVal('conntype', r.connection_type, false);
  4106. const states = r.connection_state || [];
  4107. if (states.length > 0) {
  4108. toggleFwField('cs', true);
  4109. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4110. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4111. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4112. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4113. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4114. } else {
  4115. toggleFwField('cs', false);
  4116. }
  4117. const natStates = r.connection_nat_state || [];
  4118. if (natStates.length > 0) {
  4119. toggleFwField('natstate', true);
  4120. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4121. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4122. } else {
  4123. toggleFwField('natstate', false);
  4124. }
  4125. // Advanced tab fields
  4126. setFwFieldVal('layer7', r.layer7_protocol, false);
  4127. setFwFieldVal('content', r.content, false);
  4128. setFwFieldVal('connbytes', r.connection_bytes, false);
  4129. setFwFieldVal('connrate', r.connection_rate, false);
  4130. setFwFieldVal('pcc', r.pcc, false);
  4131. setFwFieldVal('srcmac', r.src_mac_address, true);
  4132. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4133. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4134. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4135. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4136. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4137. setFwFieldVal('tlshost', r.tls_host, false);
  4138. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4139. setFwFieldVal('priority', r.priority, false);
  4140. setFwFieldVal('dscp', r.dscp, false);
  4141. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4142. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4143. setFwFieldVal('pktsize', r.packet_size, false);
  4144. setFwFieldVal('random', r.random, false);
  4145. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4146. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4147. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4148. setFwFieldVal('ttl', r.ttl, false);
  4149. // Extra tab fields
  4150. setFwFieldVal('time', r.time, false);
  4151. if (r.days) {
  4152. toggleFwField('days', true);
  4153. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4154. const chk = document.getElementById(`fw-day-${d}`);
  4155. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4156. });
  4157. } else {
  4158. toggleFwField('days', false);
  4159. }
  4160. setFwFieldVal('limit', r.limit, false);
  4161. setFwFieldVal('dstlimit', r.dst_limit, false);
  4162. setFwFieldVal('psd', r.psd, false);
  4163. // Action fields
  4164. if (r.reject_with) {
  4165. const rwEl = document.getElementById('filter-modal-rejectwith');
  4166. if (rwEl) rwEl.value = r.reject_with;
  4167. }
  4168. if (r.jump_target) {
  4169. const jtEl = document.getElementById('filter-modal-jumptarget');
  4170. if (jtEl) jtEl.value = r.jump_target;
  4171. }
  4172. if (r.address_list) {
  4173. const alEl = document.getElementById('filter-modal-action-addrlist');
  4174. if (alEl) alEl.value = r.address_list;
  4175. }
  4176. if (r.address_list_timeout) {
  4177. const toEl = document.getElementById('filter-modal-action-timeout');
  4178. if (toEl) toEl.value = r.address_list_timeout;
  4179. }
  4180. setFwFieldVal('logprefix', r.log_prefix, false);
  4181. // Statistics
  4182. const bEl = document.getElementById('fw-stat-bytes');
  4183. const pEl = document.getElementById('fw-stat-packets');
  4184. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4185. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4186. state.fwLastBytes = r.bytes || 0;
  4187. state.fwLastPackets = r.packets || 0;
  4188. state.fwLastTimestamp = Date.now();
  4189. state.fwStatRateHistory = new Array(30).fill(0);
  4190. state.fwStatPktHistory = new Array(30).fill(0);
  4191. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4192. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4193. toggleFilterActionFields();
  4194. refreshFirewallRejectTypes();
  4195. document.getElementById('filter-modal').classList.remove('hidden');
  4196. }
  4197. function closeFilterModal() {
  4198. stopFwStatPolling();
  4199. document.getElementById('filter-modal').classList.add('hidden');
  4200. }
  4201. function toggleFilterActionFields() {
  4202. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4203. const rejectBox = document.getElementById('filter-action-reject-box');
  4204. const jumpBox = document.getElementById('filter-action-jump-box');
  4205. const addrBox = document.getElementById('filter-action-addrlist-box');
  4206. if (rejectBox) {
  4207. if (act === 'reject') rejectBox.classList.remove('hidden');
  4208. else rejectBox.classList.add('hidden');
  4209. }
  4210. if (jumpBox) {
  4211. if (act === 'jump') jumpBox.classList.remove('hidden');
  4212. else jumpBox.classList.add('hidden');
  4213. }
  4214. if (addrBox) {
  4215. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4216. addrBox.classList.remove('hidden');
  4217. } else {
  4218. addrBox.classList.add('hidden');
  4219. }
  4220. }
  4221. if (act === 'log') {
  4222. const logEl = document.getElementById('filter-modal-log');
  4223. if (logEl) logEl.checked = true;
  4224. toggleFwField('logprefix', true);
  4225. }
  4226. }
  4227. function toggleFwLogPrefix() {
  4228. const isLog = document.getElementById('filter-modal-log')?.checked;
  4229. toggleFwField('logprefix', !!isLog);
  4230. }
  4231. function copyFilterRule() {
  4232. document.getElementById('filter-modal-id').value = '';
  4233. const badge = document.getElementById('fw-modal-badge');
  4234. if (badge) badge.innerText = 'New...';
  4235. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4236. }
  4237. function resetRuleCounterDisplay() {
  4238. state.fwStatRateHistory = new Array(30).fill(0);
  4239. state.fwStatPktHistory = new Array(30).fill(0);
  4240. state.fwLastBytes = 0;
  4241. state.fwLastPackets = 0;
  4242. state.fwLastTimestamp = Date.now();
  4243. const bEl = document.getElementById('fw-stat-bytes');
  4244. const pEl = document.getElementById('fw-stat-packets');
  4245. const rEl = document.getElementById('fw-stat-rate');
  4246. const prEl = document.getElementById('fw-stat-pktrate');
  4247. if (bEl) bEl.value = '0 B';
  4248. if (pEl) pEl.value = '0';
  4249. if (rEl) rEl.value = '0 bps';
  4250. if (prEl) prEl.value = '0 p/s';
  4251. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4252. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4253. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4254. }
  4255. async function resetAllFwCounters() {
  4256. try {
  4257. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4258. if (res.ok) {
  4259. resetRuleCounterDisplay();
  4260. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4261. loadFirewall(false);
  4262. }
  4263. } catch (err) {
  4264. showToast('Error', err.message, 'error');
  4265. }
  4266. }
  4267. async function applyFilterRule(closeAfter = false) {
  4268. const id = document.getElementById('filter-modal-id').value;
  4269. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4270. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4271. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4272. const chainLower = chain.toLowerCase();
  4273. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4274. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4275. switchFwRuleTab('general');
  4276. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4277. return;
  4278. }
  4279. const action = document.getElementById('filter-modal-action').value;
  4280. const comment = document.getElementById('filter-modal-comment').value.trim();
  4281. const enabled = document.getElementById('filter-modal-enabled').checked;
  4282. const src = getFwFieldVal('src', true);
  4283. const dst = getFwFieldVal('dst', true);
  4284. const srclist = getFwFieldVal('srclist', true);
  4285. const dstlist = getFwFieldVal('dstlist', true);
  4286. const srcgeo = getFwFieldVal('srcgeo', true);
  4287. const dstgeo = getFwFieldVal('dstgeo', true);
  4288. const proto = getFwFieldVal('proto', true);
  4289. const sport = getFwFieldVal('sport', true);
  4290. const dport = getFwFieldVal('dport', true);
  4291. const anyport = getFwFieldVal('anyport', true);
  4292. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4293. switchFwRuleTab('general'); toggleFwField('proto', true);
  4294. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4295. }
  4296. let iniface = getFwFieldVal('iniface', true);
  4297. let outiface = getFwFieldVal('outiface', true);
  4298. let inifacelist = getFwFieldVal('inifacelist', true);
  4299. let outifacelist = getFwFieldVal('outifacelist', true);
  4300. if (chainLower === 'input') {
  4301. outiface = '';
  4302. outifacelist = '';
  4303. } else if (chainLower === 'output') {
  4304. iniface = '';
  4305. inifacelist = '';
  4306. }
  4307. const pktmark = getFwFieldVal('pktmark', true);
  4308. const connmark = getFwFieldVal('connmark', true);
  4309. const routingmark = getFwFieldVal('routingmark', true);
  4310. const conntype = getFwFieldVal('conntype', false);
  4311. const states = [];
  4312. const csBox = document.getElementById('fw-field-cs');
  4313. if (csBox && !csBox.classList.contains('hidden')) {
  4314. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4315. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4316. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4317. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4318. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4319. }
  4320. const natStates = [];
  4321. const natBox = document.getElementById('fw-field-natstate');
  4322. if (natBox && !natBox.classList.contains('hidden')) {
  4323. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4324. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4325. }
  4326. const payload = {
  4327. ip_version: Number(document.getElementById('filter-modal-family').value),
  4328. id,
  4329. chain,
  4330. action,
  4331. protocol: proto || 'all',
  4332. src_address: src,
  4333. dst_address: dst,
  4334. src_port: sport,
  4335. dst_port: dport,
  4336. any_port: anyport,
  4337. in_interface: iniface,
  4338. out_interface: outiface,
  4339. in_interface_list: inifacelist,
  4340. out_interface_list: outifacelist,
  4341. packet_mark: pktmark,
  4342. connection_mark: connmark,
  4343. routing_mark: routingmark,
  4344. connection_type: conntype,
  4345. connection_state: states,
  4346. connection_nat_state: natStates,
  4347. src_address_list: srclist,
  4348. dst_address_list: dstlist,
  4349. src_geoip: srcgeo,
  4350. dst_geoip: dstgeo,
  4351. comment,
  4352. disabled: !enabled,
  4353. // Advanced tab
  4354. content: getFwFieldVal('content', false),
  4355. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4356. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4357. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4358. ipsec_policy: getFwFieldVal('ipsec', false),
  4359. dscp: getFwFieldVal('dscp', false),
  4360. tcp_mss: getFwFieldVal('tcpmss', false),
  4361. tos: document.getElementById('fw-val-tos')?.value || '',
  4362. packet_size: getFwFieldVal('pktsize', false),
  4363. random: getFwFieldVal('random', false),
  4364. tcp_flags: getFwFieldVal('tcpflags', false),
  4365. icmp_options: getFwFieldVal('icmpoptions', false),
  4366. ttl: getFwFieldVal('ttl', false),
  4367. days: selectedDays,
  4368. // Extra tab
  4369. time: getFwFieldVal('time', false),
  4370. limit: getFwFieldVal('limit', false),
  4371. // Action tab
  4372. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4373. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4374. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4375. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4376. log: document.getElementById('filter-modal-log')?.checked || false,
  4377. log_prefix: getFwFieldVal('logprefix', false)
  4378. };
  4379. try {
  4380. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4381. method: 'POST',
  4382. headers: { 'Content-Type': 'application/json' },
  4383. body: JSON.stringify(payload)
  4384. });
  4385. if (res.ok) {
  4386. const data = await res.json();
  4387. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4388. loadFirewall(false);
  4389. if (closeAfter) {
  4390. closeFilterModal();
  4391. } else {
  4392. if (data.id) {
  4393. document.getElementById('filter-modal-id').value = data.id;
  4394. const badge = document.getElementById('fw-modal-badge');
  4395. if (badge) badge.innerText = `#${data.id}`;
  4396. }
  4397. }
  4398. } else {
  4399. const err = await res.json();
  4400. showToast('Error', err.message || 'Failed to save rule', 'error');
  4401. }
  4402. } catch (err) {
  4403. showToast('Error', err.message, 'error');
  4404. }
  4405. }
  4406. function submitSaveFilterRule(e) {
  4407. if (e && e.preventDefault) e.preventDefault();
  4408. return applyFilterRule(true);
  4409. }
  4410. function startFwStatPolling() {
  4411. stopFwStatPolling();
  4412. pollRuleStats();
  4413. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4414. }
  4415. function stopFwStatPolling() {
  4416. if (state.fwStatInterval) {
  4417. clearInterval(state.fwStatInterval);
  4418. state.fwStatInterval = null;
  4419. }
  4420. }
  4421. async function pollRuleStats() {
  4422. const id = document.getElementById('filter-modal-id')?.value;
  4423. if (!id) {
  4424. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4425. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4426. return;
  4427. }
  4428. try {
  4429. const res = await fetch(`${API_BASE}/firewall/filter`);
  4430. if (!res.ok) return;
  4431. const rules = await res.json();
  4432. const r = rules.find(x => x.id === id);
  4433. if (!r) return;
  4434. const now = Date.now();
  4435. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4436. state.fwLastTimestamp = now;
  4437. const curBytes = r.bytes || 0;
  4438. const curPackets = r.packets || 0;
  4439. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4440. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4441. state.fwLastBytes = curBytes;
  4442. state.fwLastPackets = curPackets;
  4443. const rateBps = Math.round((deltaBytes * 8) / dt);
  4444. const ratePkt = Math.round(deltaPkts / dt);
  4445. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4446. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4447. state.fwStatRateHistory.push(rateBps);
  4448. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4449. state.fwStatPktHistory.push(ratePkt);
  4450. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4451. const bEl = document.getElementById('fw-stat-bytes');
  4452. const pEl = document.getElementById('fw-stat-packets');
  4453. const rEl = document.getElementById('fw-stat-rate');
  4454. const prEl = document.getElementById('fw-stat-pktrate');
  4455. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4456. if (pEl) pEl.value = curPackets.toLocaleString();
  4457. if (rEl) rEl.value = formatBps(rateBps);
  4458. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4459. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4460. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4461. } catch (e) {
  4462. console.error('Error polling rule stats', e);
  4463. }
  4464. }
  4465. function formatBps(bps) {
  4466. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4467. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4468. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4469. return bps + ' bps';
  4470. }
  4471. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4472. const svg = document.getElementById(svgId);
  4473. if (!svg) return;
  4474. const w = 500;
  4475. const h = 100;
  4476. const paddingRight = 45;
  4477. const graphWidth = w - paddingRight;
  4478. const maxVal = Math.max(5, ...dataArray);
  4479. const currentVal = dataArray[dataArray.length - 1] || 0;
  4480. const leg = document.getElementById(legendId);
  4481. if (leg) {
  4482. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4483. }
  4484. let gridLines = '';
  4485. for (let i = 0; i <= 5; i++) {
  4486. const y = 8 + (i * (h - 18) / 5);
  4487. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4488. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4489. gridLines += `
  4490. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4491. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4492. `;
  4493. }
  4494. const step = graphWidth / (dataArray.length - 1);
  4495. const points = dataArray.map((val, idx) => {
  4496. const x = idx * step;
  4497. const y = (h - 10) - (val / maxVal) * (h - 20);
  4498. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4499. });
  4500. const polylineStr = points.join(' ');
  4501. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4502. svg.innerHTML = `
  4503. ${gridLines}
  4504. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4505. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4506. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4507. `;
  4508. }
  4509. async function moveFilterRule(id, dir) {
  4510. id = decodeURIComponent(id);
  4511. try {
  4512. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4513. method: 'POST',
  4514. headers: { 'Content-Type': 'application/json' },
  4515. body: JSON.stringify({ direction: dir })
  4516. });
  4517. if (!res.ok) throw new Error(await responseError(res));
  4518. await loadFirewall(false);
  4519. } catch (err) {
  4520. showToast('Error', err.message, 'error');
  4521. }
  4522. }
  4523. async function toggleFilterRuleState(id, disabled) {
  4524. id = decodeURIComponent(id);
  4525. try {
  4526. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4527. method: 'POST',
  4528. headers: { 'Content-Type': 'application/json' },
  4529. body: JSON.stringify({ disabled })
  4530. });
  4531. if (!res.ok) throw new Error(await responseError(res));
  4532. await loadFirewall(false);
  4533. } catch (err) {
  4534. showToast('Error', err.message, 'error');
  4535. }
  4536. }
  4537. async function deleteFilterRule(id) {
  4538. id = decodeURIComponent(id);
  4539. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4540. try {
  4541. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4542. if (!res.ok) throw new Error(await responseError(res));
  4543. {
  4544. showToast('Deleted', 'Filter rule removed', 'success');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- NAT Rules -----------------
  4552. function renderNATRules() {
  4553. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4554. const tbody = document.getElementById('nat-table-body');
  4555. const empty = document.getElementById('nat-empty');
  4556. if (!tbody) return;
  4557. tbody.innerHTML = '';
  4558. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4559. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4560. if (rules.length === 0) {
  4561. empty?.classList.remove('hidden');
  4562. return;
  4563. }
  4564. empty?.classList.add('hidden');
  4565. rules.forEach((raw, idx) => {
  4566. const r = safeFirewallRow(raw);
  4567. const tr = document.createElement('tr');
  4568. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4569. let toTarget = '-';
  4570. if (r.action === 'jump') {
  4571. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4572. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4573. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4574. } else if (r.action === 'redirect') {
  4575. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4576. } else if (r.action === 'masquerade') {
  4577. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  4578. } else if (r.action === 'log') {
  4579. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4580. } else {
  4581. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4582. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4583. }
  4584. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4585. tr.innerHTML = `
  4586. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4587. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4588. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4589. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4590. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4591. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  4592. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4593. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4594. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4595. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4596. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4597. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4598. </td>
  4599. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4600. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4601. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4602. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4603. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4604. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4605. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4606. </td>
  4607. `;
  4608. tbody.appendChild(tr);
  4609. });
  4610. }
  4611. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4612. function switchNATRuleTab(tab) {
  4613. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4614. state.activeNATRuleTab = tab;
  4615. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4616. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4617. btn.classList.add('text-slate-400', 'border-transparent');
  4618. });
  4619. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4620. if (activeBtn) {
  4621. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4622. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4623. }
  4624. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4625. const activePane = document.getElementById(`nat-pane-${tab}`);
  4626. if (activePane) activePane.classList.remove('hidden');
  4627. if (tab === 'statistics') {
  4628. startNATStatPolling();
  4629. } else {
  4630. stopNATStatPolling();
  4631. }
  4632. }
  4633. function toggleNATField(fieldKey, expand) {
  4634. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4635. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4636. if (!plusBtn || !fieldBox) return;
  4637. if (expand) {
  4638. plusBtn.classList.add('hidden');
  4639. fieldBox.classList.remove('hidden');
  4640. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4641. if (valInput) valInput.focus();
  4642. } else {
  4643. fieldBox.classList.add('hidden');
  4644. plusBtn.classList.remove('hidden');
  4645. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4646. if (valInput) {
  4647. if (valInput.tagName === 'SELECT') {
  4648. valInput.selectedIndex = 0;
  4649. } else {
  4650. valInput.value = '';
  4651. }
  4652. }
  4653. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4654. if (invInput) invInput.checked = false;
  4655. if (fieldKey === 'days') {
  4656. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4657. const el = document.getElementById(`nat-day-${d}`);
  4658. if (el) el.checked = true;
  4659. });
  4660. }
  4661. }
  4662. }
  4663. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4664. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4665. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4666. toggleNATField(fieldKey, true);
  4667. let strVal = String(value);
  4668. if (hasInvert) {
  4669. const inv = strVal.startsWith('!');
  4670. if (inv) strVal = strVal.slice(1);
  4671. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4672. if (invEl) invEl.checked = inv;
  4673. else if (inv) strVal = '!'+strVal;
  4674. }
  4675. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4676. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  4677. } else {
  4678. toggleNATField(fieldKey, false);
  4679. }
  4680. }
  4681. function getNATFieldVal(fieldKey, hasInvert = false) {
  4682. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4683. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4684. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4685. let v = valEl ? valEl.value.trim() : '';
  4686. if (!v) return '';
  4687. if (hasInvert) {
  4688. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4689. if (invEl && invEl.checked) {
  4690. v = '!' + v.replace(/^!/, '');
  4691. }
  4692. }
  4693. return v;
  4694. }
  4695. function toggleMaximizeNATModal() {
  4696. const win = document.getElementById('nat-modal-window');
  4697. if (!win) return;
  4698. if (win.classList.contains('max-w-[720px]')) {
  4699. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4700. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4701. } else {
  4702. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4703. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4704. }
  4705. }
  4706. function syncNATChainFromSelect() {
  4707. const sel = document.getElementById('nat-modal-chain-select');
  4708. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4709. const customInput = document.getElementById('nat-modal-custom-input');
  4710. const chainInput = document.getElementById('nat-modal-chain');
  4711. if (!sel || !chainInput) return;
  4712. if (sel.value === '__custom__') {
  4713. if (customWrap) customWrap.classList.remove('hidden');
  4714. if (customInput) {
  4715. customInput.value = '';
  4716. customInput.focus();
  4717. }
  4718. chainInput.value = '';
  4719. } else {
  4720. if (customWrap) customWrap.classList.add('hidden');
  4721. chainInput.value = sel.value;
  4722. const actEl = document.getElementById('nat-modal-action');
  4723. if (actEl) {
  4724. const curAct = actEl.value;
  4725. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4726. actEl.value = 'dst-nat';
  4727. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4728. actEl.value = 'masquerade';
  4729. }
  4730. }
  4731. }
  4732. handleNATChainChange();
  4733. }
  4734. function syncNATCustomChainInput() {
  4735. const customInput = document.getElementById('nat-modal-custom-input');
  4736. const chainInput = document.getElementById('nat-modal-chain');
  4737. if (customInput && chainInput) {
  4738. chainInput.value = customInput.value.trim();
  4739. }
  4740. handleNATChainChange();
  4741. }
  4742. function handleNATChainChange() {
  4743. const chainInput = document.getElementById('nat-modal-chain');
  4744. const rawChain = (chainInput?.value || 'postrouting').trim();
  4745. const chain = nativeNATChain(rawChain).toLowerCase();
  4746. const sel = document.getElementById('nat-modal-chain-select');
  4747. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4748. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4749. sel.value = chain;
  4750. }
  4751. }
  4752. const hintEl = document.getElementById('nat-chain-hint');
  4753. if (hintEl) {
  4754. if (chain === 'prerouting') {
  4755. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4756. } else if (chain === 'postrouting') {
  4757. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4758. } else if (chain === 'output') {
  4759. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4760. } else if (chain === 'input') {
  4761. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4762. } else {
  4763. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4764. }
  4765. }
  4766. const rowIn = document.getElementById('nat-row-iniface');
  4767. const rowInList = document.getElementById('nat-row-inifacelist');
  4768. const rowOut = document.getElementById('nat-row-outiface');
  4769. const rowOutList = document.getElementById('nat-row-outifacelist');
  4770. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4771. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4772. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4773. if (chain === 'prerouting' || chain === 'input') {
  4774. if (rowIn) rowIn.classList.remove('hidden');
  4775. if (rowInList) rowInList.classList.remove('hidden');
  4776. if (rowOut) rowOut.classList.add('hidden');
  4777. if (rowOutList) rowOutList.classList.add('hidden');
  4778. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4779. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4780. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4781. } else if (chain === 'postrouting' || chain === 'output') {
  4782. if (rowIn) rowIn.classList.add('hidden');
  4783. if (rowInList) rowInList.classList.add('hidden');
  4784. if (rowOut) rowOut.classList.remove('hidden');
  4785. if (rowOutList) rowOutList.classList.remove('hidden');
  4786. if (rowInBridge) rowInBridge.classList.add('hidden');
  4787. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4788. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4789. } else {
  4790. if (rowIn) rowIn.classList.remove('hidden');
  4791. if (rowInList) rowInList.classList.remove('hidden');
  4792. if (rowOut) rowOut.classList.remove('hidden');
  4793. if (rowOutList) rowOutList.classList.remove('hidden');
  4794. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4795. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4796. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4797. }
  4798. checkNATActionChainCompatibility();
  4799. toggleNATActionFields();
  4800. }
  4801. function checkNATActionChainCompatibility() {
  4802. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4803. const chain = nativeNATChain(rawChain).toLowerCase();
  4804. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4805. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4806. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4807. if (!warnBox || !warnMsg) return;
  4808. let msg = '';
  4809. if (['dst-nat', 'redirect'].includes(action)) {
  4810. if (chain !== 'prerouting' && chain !== 'output') {
  4811. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4812. }
  4813. } else if (action === 'masquerade') {
  4814. if (chain !== 'postrouting') {
  4815. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4816. }
  4817. } else if (action === 'src-nat') {
  4818. if (chain !== 'postrouting' && chain !== 'input') {
  4819. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4820. }
  4821. }
  4822. if (msg) {
  4823. warnMsg.textContent = msg;
  4824. warnBox.classList.remove('hidden');
  4825. } else {
  4826. warnBox.classList.add('hidden');
  4827. }
  4828. }
  4829. function toggleNATActionFields() {
  4830. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4831. const rowAddr = document.getElementById('nat-row-toaddr');
  4832. const rowPort = document.getElementById('nat-row-toport');
  4833. const jumpBox = document.getElementById('nat-action-jump-box');
  4834. const addrBox = document.getElementById('nat-action-addrlist-box');
  4835. // Hide all dynamic rows first
  4836. if (rowAddr) rowAddr.classList.add('hidden');
  4837. if (rowPort) rowPort.classList.add('hidden');
  4838. if (jumpBox) jumpBox.classList.add('hidden');
  4839. if (addrBox) addrBox.classList.add('hidden');
  4840. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4841. if (rowAddr) rowAddr.classList.remove('hidden');
  4842. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4843. } else if (act === 'redirect' || act === 'masquerade') {
  4844. if (rowPort) rowPort.classList.remove('hidden');
  4845. } else if (act === 'jump') {
  4846. if (jumpBox) jumpBox.classList.remove('hidden');
  4847. } else if (act.includes('address-list') || act.includes('address list')) {
  4848. if (addrBox) addrBox.classList.remove('hidden');
  4849. }
  4850. if (act === 'log') {
  4851. const logEl = document.getElementById('nat-modal-log');
  4852. if (logEl) logEl.checked = true;
  4853. toggleNATField('logprefix', true);
  4854. }
  4855. }
  4856. function handleNATActionChange() {
  4857. toggleNATActionFields();
  4858. checkNATActionChainCompatibility();
  4859. }
  4860. function toggleNATLogPrefix() {
  4861. const isLog = document.getElementById('nat-modal-log')?.checked;
  4862. toggleNATField('logprefix', !!isLog);
  4863. }
  4864. function openAddNATModal() {
  4865. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4866. switchNATRuleTab('general');
  4867. setFirewallDays('nat', '');
  4868. const badge = document.getElementById('nat-modal-badge');
  4869. if (badge) badge.innerText = 'New...';
  4870. document.getElementById('nat-modal-id').value = '';
  4871. document.getElementById('nat-modal-family').value = '4';
  4872. document.getElementById('nat-modal-enabled').checked = true;
  4873. document.getElementById('nat-modal-comment').value = '';
  4874. document.getElementById('nat-modal-chain').value = 'postrouting';
  4875. populateChainDropdown('nat', 'postrouting');
  4876. handleNATChainChange();
  4877. document.getElementById('nat-modal-action').value = 'masquerade';
  4878. document.getElementById('nat-modal-toaddr').value = '';
  4879. document.getElementById('nat-modal-toport').value = '';
  4880. document.getElementById('nat-modal-log').checked = false;
  4881. populateInterfaceSelect('nat-val-iniface');
  4882. populateInterfaceSelect('nat-val-outiface');
  4883. populateAddressListSelect('nat-val-srclist');
  4884. populateAddressListSelect('nat-val-dstlist');
  4885. populateGeoIPSelect('nat-val-srcgeo');
  4886. populateGeoIPSelect('nat-val-dstgeo');
  4887. const allFieldKeys = [
  4888. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4889. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4890. 'routingmark', 'conntype',
  4891. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4892. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4893. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4894. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4895. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4896. ];
  4897. allFieldKeys.forEach(k => toggleNATField(k, false));
  4898. resetNATCounterDisplay();
  4899. toggleNATActionFields();
  4900. document.getElementById('nat-modal').classList.remove('hidden');
  4901. }
  4902. function openEditNATModal(id) {
  4903. id = decodeURIComponent(id);
  4904. const r = (state.natRules || []).find(rule => rule.id === id);
  4905. if (!r) return;
  4906. setFirewallDays('nat', r.days || '');
  4907. switchNATRuleTab('general');
  4908. const badge = document.getElementById('nat-modal-badge');
  4909. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4910. document.getElementById('nat-modal-id').value = r.id;
  4911. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4912. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4913. document.getElementById('nat-modal-comment').value = r.comment || '';
  4914. const natChain = nativeNATChain(r.chain || 'postrouting');
  4915. document.getElementById('nat-modal-chain').value = natChain;
  4916. populateChainDropdown('nat', natChain);
  4917. handleNATChainChange();
  4918. setFirewallActionSelection('nat', r.action || 'accept');
  4919. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4920. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4921. document.getElementById('nat-modal-log').checked = !!r.log;
  4922. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4923. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4924. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4925. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4926. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4927. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4928. setNATFieldVal('src', r.src_address, true);
  4929. setNATFieldVal('dst', r.dst_address, true);
  4930. setNATFieldVal('srclist', r.src_address_list, true);
  4931. setNATFieldVal('dstlist', r.dst_address_list, true);
  4932. setNATFieldVal('srcgeo', r.src_geoip, true);
  4933. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4934. if (r.protocol && r.protocol !== 'all') {
  4935. setNATFieldVal('proto', r.protocol, true);
  4936. } else {
  4937. toggleNATField('proto', false);
  4938. }
  4939. setNATFieldVal('sport', r.src_port, true);
  4940. setNATFieldVal('dport', r.dst_port, true);
  4941. setNATFieldVal('anyport', r.any_port, true);
  4942. setNATFieldVal('iniface', r.in_interface, true);
  4943. setNATFieldVal('outiface', r.out_interface, true);
  4944. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4945. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4946. setNATFieldVal('pktmark', r.packet_mark, true);
  4947. setNATFieldVal('connmark', r.connection_mark, true);
  4948. setNATFieldVal('routingmark', r.routing_mark, true);
  4949. setNATFieldVal('conntype', r.connection_type, false);
  4950. // Advanced tab fields
  4951. setNATFieldVal('layer7', r.layer7_protocol, false);
  4952. setNATFieldVal('content', r.content, false);
  4953. setNATFieldVal('connbytes', r.connection_bytes, false);
  4954. setNATFieldVal('connrate', r.connection_rate, false);
  4955. setNATFieldVal('pcc', r.pcc, false);
  4956. setNATFieldVal('srcmac', r.src_mac_address, true);
  4957. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4958. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4959. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4960. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4961. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4962. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4963. setNATFieldVal('priority', r.priority, false);
  4964. setNATFieldVal('dscp', r.dscp, false);
  4965. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4966. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4967. setNATFieldVal('pktsize', r.packet_size, false);
  4968. setNATFieldVal('random', r.random, false);
  4969. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4970. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4971. setNATFieldVal('ttl', r.ttl, false);
  4972. // Extra tab fields
  4973. setNATFieldVal('time', r.time, false);
  4974. if (r.days) {
  4975. toggleNATField('days', true);
  4976. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4977. const chk = document.getElementById(`nat-day-${d}`);
  4978. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4979. });
  4980. } else {
  4981. toggleNATField('days', false);
  4982. }
  4983. setNATFieldVal('limit', r.limit, false);
  4984. setNATFieldVal('dstlimit', r.dst_limit, false);
  4985. setNATFieldVal('psd', r.psd, false);
  4986. // Action fields
  4987. if (r.jump_target) {
  4988. const jtEl = document.getElementById('nat-modal-jumptarget');
  4989. if (jtEl) jtEl.value = r.jump_target;
  4990. }
  4991. if (r.address_list) {
  4992. const alEl = document.getElementById('nat-modal-action-addrlist');
  4993. if (alEl) alEl.value = r.address_list;
  4994. }
  4995. if (r.address_list_timeout) {
  4996. const toEl = document.getElementById('nat-modal-action-timeout');
  4997. if (toEl) toEl.value = r.address_list_timeout;
  4998. }
  4999. setNATFieldVal('logprefix', r.log_prefix, false);
  5000. // Statistics
  5001. const bEl = document.getElementById('nat-stat-bytes');
  5002. const pEl = document.getElementById('nat-stat-packets');
  5003. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5004. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5005. state.natLastBytes = r.bytes || 0;
  5006. state.natLastPackets = r.packets || 0;
  5007. state.natLastTimestamp = Date.now();
  5008. state.natStatRateHistory = new Array(30).fill(0);
  5009. state.natStatPktHistory = new Array(30).fill(0);
  5010. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5011. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5012. toggleNATActionFields();
  5013. document.getElementById('nat-modal').classList.remove('hidden');
  5014. }
  5015. function closeNATModal() {
  5016. stopNATStatPolling();
  5017. document.getElementById('nat-modal').classList.add('hidden');
  5018. }
  5019. function copyNATRule() {
  5020. document.getElementById('nat-modal-id').value = '';
  5021. const badge = document.getElementById('nat-modal-badge');
  5022. if (badge) badge.innerText = 'New...';
  5023. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5024. }
  5025. function resetNATCounterDisplay() {
  5026. state.natStatRateHistory = new Array(30).fill(0);
  5027. state.natStatPktHistory = new Array(30).fill(0);
  5028. state.natLastBytes = 0;
  5029. state.natLastPackets = 0;
  5030. state.natLastTimestamp = Date.now();
  5031. const bEl = document.getElementById('nat-stat-bytes');
  5032. const pEl = document.getElementById('nat-stat-packets');
  5033. const rEl = document.getElementById('nat-stat-rate');
  5034. const prEl = document.getElementById('nat-stat-pktrate');
  5035. if (bEl) bEl.value = '0 B';
  5036. if (pEl) pEl.value = '0';
  5037. if (rEl) rEl.value = '0 bps';
  5038. if (prEl) prEl.value = '0 p/s';
  5039. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5040. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5041. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5042. }
  5043. async function applyNATRule(closeAfter = false) {
  5044. const id = document.getElementById('nat-modal-id').value;
  5045. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5046. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5047. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5048. const chainLower = nativeNATChain(chain).toLowerCase();
  5049. const action = document.getElementById('nat-modal-action').value;
  5050. const comment = document.getElementById('nat-modal-comment').value.trim();
  5051. const enabled = document.getElementById('nat-modal-enabled').checked;
  5052. const src = getNATFieldVal('src', true);
  5053. const dst = getNATFieldVal('dst', true);
  5054. const srclist = getNATFieldVal('srclist', true);
  5055. const dstlist = getNATFieldVal('dstlist', true);
  5056. const srcgeo = getNATFieldVal('srcgeo', true);
  5057. const dstgeo = getNATFieldVal('dstgeo', true);
  5058. const proto = getNATFieldVal('proto', true);
  5059. const sport = getNATFieldVal('sport', true);
  5060. const dport = getNATFieldVal('dport', true);
  5061. const anyport = getNATFieldVal('anyport', true);
  5062. let iniface = getNATFieldVal('iniface', true);
  5063. let outiface = getNATFieldVal('outiface', true);
  5064. let inifacelist = getNATFieldVal('inifacelist', true);
  5065. let outifacelist = getNATFieldVal('outifacelist', true);
  5066. if (chainLower === 'prerouting' || chainLower === 'input') {
  5067. outiface = '';
  5068. outifacelist = '';
  5069. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5070. iniface = '';
  5071. inifacelist = '';
  5072. }
  5073. const pktmark = getNATFieldVal('pktmark', true);
  5074. const connmark = getNATFieldVal('connmark', true);
  5075. const routingmark = getNATFieldVal('routingmark', true);
  5076. const conntype = getNATFieldVal('conntype', false);
  5077. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5078. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5079. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5080. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5081. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5082. switchNATRuleTab('general');
  5083. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5084. return;
  5085. }
  5086. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5087. switchNATRuleTab('general');
  5088. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5089. return;
  5090. }
  5091. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5092. switchNATRuleTab('general');
  5093. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5094. return;
  5095. }
  5096. if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
  5097. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5098. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5099. showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
  5100. }
  5101. const payload = {
  5102. ip_version: Number(document.getElementById('nat-modal-family').value),
  5103. id,
  5104. chain,
  5105. action,
  5106. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5107. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5108. protocol: proto || 'all',
  5109. src_address: src,
  5110. dst_address: dst,
  5111. src_port: sport,
  5112. dst_port: dport,
  5113. any_port: anyport,
  5114. in_interface: iniface,
  5115. out_interface: outiface,
  5116. in_interface_list: inifacelist,
  5117. out_interface_list: outifacelist,
  5118. packet_mark: pktmark,
  5119. connection_mark: connmark,
  5120. routing_mark: routingmark,
  5121. connection_type: conntype,
  5122. src_address_list: srclist,
  5123. dst_address_list: dstlist,
  5124. src_geoip: srcgeo,
  5125. dst_geoip: dstgeo,
  5126. comment,
  5127. disabled: !enabled,
  5128. // Advanced tab
  5129. content: getNATFieldVal('content', false),
  5130. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5131. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5132. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5133. ipsec_policy: getNATFieldVal('ipsec', false),
  5134. dscp: getNATFieldVal('dscp', false),
  5135. tcp_mss: getNATFieldVal('tcpmss', false),
  5136. tos: document.getElementById('nat-val-tos')?.value || '',
  5137. packet_size: getNATFieldVal('pktsize', false),
  5138. random: getNATFieldVal('random', false),
  5139. icmp_options: getNATFieldVal('icmpoptions', false),
  5140. ttl: getNATFieldVal('ttl', false),
  5141. days: selectedDays,
  5142. // Extra tab
  5143. time: getNATFieldVal('time', false),
  5144. limit: getNATFieldVal('limit', false),
  5145. // Action tab
  5146. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5147. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5148. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5149. log: document.getElementById('nat-modal-log')?.checked || false,
  5150. log_prefix: getNATFieldVal('logprefix', false)
  5151. };
  5152. try {
  5153. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5154. method: 'POST',
  5155. headers: { 'Content-Type': 'application/json' },
  5156. body: JSON.stringify(payload)
  5157. });
  5158. if (res.ok) {
  5159. const data = await res.json();
  5160. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5161. loadFirewall(false);
  5162. if (closeAfter) {
  5163. closeNATModal();
  5164. } else {
  5165. if (data.id) {
  5166. document.getElementById('nat-modal-id').value = data.id;
  5167. const badge = document.getElementById('nat-modal-badge');
  5168. if (badge) badge.innerText = `#${data.id}`;
  5169. }
  5170. }
  5171. } else {
  5172. const err = await res.json();
  5173. showToast('Error', err.message || 'Failed to save rule', 'error');
  5174. }
  5175. } catch (err) {
  5176. showToast('Error', err.message, 'error');
  5177. }
  5178. }
  5179. function submitSaveNATRule(e) {
  5180. if (e && e.preventDefault) e.preventDefault();
  5181. return applyNATRule(true);
  5182. }
  5183. function startNATStatPolling() {
  5184. stopNATStatPolling();
  5185. pollNATRuleStats();
  5186. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5187. }
  5188. function stopNATStatPolling() {
  5189. if (state.natStatInterval) {
  5190. clearInterval(state.natStatInterval);
  5191. state.natStatInterval = null;
  5192. }
  5193. }
  5194. async function pollNATRuleStats() {
  5195. const id = document.getElementById('nat-modal-id')?.value;
  5196. if (!id) {
  5197. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5198. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5199. return;
  5200. }
  5201. try {
  5202. const res = await fetch(`${API_BASE}/firewall/nat`);
  5203. if (!res.ok) return;
  5204. const rules = await res.json();
  5205. const r = rules.find(x => x.id === id);
  5206. if (!r) return;
  5207. const now = Date.now();
  5208. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5209. state.natLastTimestamp = now;
  5210. const curBytes = r.bytes || 0;
  5211. const curPackets = r.packets || 0;
  5212. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5213. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5214. state.natLastBytes = curBytes;
  5215. state.natLastPackets = curPackets;
  5216. const rateBps = Math.round((deltaBytes * 8) / dt);
  5217. const ratePkt = Math.round(deltaPkts / dt);
  5218. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5219. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5220. state.natStatRateHistory.push(rateBps);
  5221. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5222. state.natStatPktHistory.push(ratePkt);
  5223. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5224. const bEl = document.getElementById('nat-stat-bytes');
  5225. const pEl = document.getElementById('nat-stat-packets');
  5226. const rEl = document.getElementById('nat-stat-rate');
  5227. const prEl = document.getElementById('nat-stat-pktrate');
  5228. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5229. if (pEl) pEl.value = curPackets.toLocaleString();
  5230. if (rEl) rEl.value = formatBps(rateBps);
  5231. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5232. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5233. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5234. } catch (e) {
  5235. console.error('Error polling NAT rule stats', e);
  5236. }
  5237. }
  5238. async function moveNATRule(id, dir) {
  5239. id = decodeURIComponent(id);
  5240. try {
  5241. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5242. method: 'POST',
  5243. headers: { 'Content-Type': 'application/json' },
  5244. body: JSON.stringify({ direction: dir })
  5245. });
  5246. if (!res.ok) throw new Error(await responseError(res));
  5247. await loadFirewall(false);
  5248. } catch (err) {
  5249. showToast('Error', err.message, 'error');
  5250. }
  5251. }
  5252. async function toggleNATRuleState(id, disabled) {
  5253. id = decodeURIComponent(id);
  5254. try {
  5255. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5256. method: 'POST',
  5257. headers: { 'Content-Type': 'application/json' },
  5258. body: JSON.stringify({ disabled })
  5259. });
  5260. if (!res.ok) throw new Error(await responseError(res));
  5261. await loadFirewall(false);
  5262. } catch (err) {
  5263. showToast('Error', err.message, 'error');
  5264. }
  5265. }
  5266. async function deleteNATRule(id) {
  5267. id = decodeURIComponent(id);
  5268. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5269. try {
  5270. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5271. if (!res.ok) throw new Error(await responseError(res));
  5272. {
  5273. showToast('Deleted', 'NAT rule removed', 'success');
  5274. loadFirewall(false);
  5275. }
  5276. } catch (err) {
  5277. showToast('Error', err.message, 'error');
  5278. }
  5279. }
  5280. // ----------------- Mangle Rules -----------------
  5281. function renderMangleRules() {
  5282. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5283. const tbody = document.getElementById('mangle-table-body');
  5284. const empty = document.getElementById('mangle-empty');
  5285. if (!tbody) return;
  5286. tbody.innerHTML = '';
  5287. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5288. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5289. if (rules.length === 0) {
  5290. empty?.classList.remove('hidden');
  5291. return;
  5292. }
  5293. empty?.classList.add('hidden');
  5294. rules.forEach((raw, idx) => {
  5295. const r = safeFirewallRow(raw);
  5296. const tr = document.createElement('tr');
  5297. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5298. let markVal = '<span class="text-slate-500">-</span>';
  5299. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5300. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5301. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5302. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5303. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5304. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5305. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5306. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5307. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5308. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5309. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  5310. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5311. tr.innerHTML = `
  5312. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5313. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5314. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5315. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5316. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5317. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5318. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5319. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  5320. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5321. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5322. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5323. </td>
  5324. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5325. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5326. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5327. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5328. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  5329. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5330. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5331. </td>
  5332. `;
  5333. tbody.appendChild(tr);
  5334. });
  5335. }
  5336. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5337. function switchMangleRuleTab(tab) {
  5338. state.activeMangleRuleTab = tab;
  5339. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5340. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5341. btn.classList.add('text-slate-400', 'border-transparent');
  5342. });
  5343. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5344. if (activeBtn) {
  5345. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5346. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5347. }
  5348. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5349. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5350. if (activePane) activePane.classList.remove('hidden');
  5351. if (tab === 'statistics') {
  5352. startMangleStatPolling();
  5353. } else {
  5354. stopMangleStatPolling();
  5355. }
  5356. }
  5357. function toggleMangleField(fieldKey, expand) {
  5358. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5359. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5360. if (!plusBtn || !fieldBox) return;
  5361. if (expand) {
  5362. plusBtn.classList.add('hidden');
  5363. fieldBox.classList.remove('hidden');
  5364. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5365. if (valInput) valInput.focus();
  5366. } else {
  5367. fieldBox.classList.add('hidden');
  5368. plusBtn.classList.remove('hidden');
  5369. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5370. if (valInput) {
  5371. if (valInput.tagName === 'SELECT') {
  5372. valInput.selectedIndex = 0;
  5373. } else {
  5374. valInput.value = '';
  5375. }
  5376. }
  5377. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5378. if (invInput) invInput.checked = false;
  5379. if (fieldKey === 'cs') {
  5380. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5381. const el = document.getElementById(id);
  5382. if (el) el.checked = false;
  5383. });
  5384. }
  5385. if (fieldKey === 'natstate') {
  5386. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5387. const el = document.getElementById(id);
  5388. if (el) el.checked = false;
  5389. });
  5390. }
  5391. }
  5392. }
  5393. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5394. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5395. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5396. toggleMangleField(fieldKey, true);
  5397. let strVal = String(value);
  5398. if (hasInvert) {
  5399. const inv = strVal.startsWith('!');
  5400. if (inv) strVal = strVal.slice(1);
  5401. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5402. if (invEl) invEl.checked = inv;
  5403. else if (inv) strVal = '!'+strVal;
  5404. }
  5405. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5406. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  5407. } else {
  5408. toggleMangleField(fieldKey, false);
  5409. }
  5410. }
  5411. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5412. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5413. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5414. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5415. let v = valEl ? valEl.value.trim() : '';
  5416. if (!v) return '';
  5417. if (hasInvert) {
  5418. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5419. if (invEl && invEl.checked) {
  5420. v = '!' + v.replace(/^!/, '');
  5421. }
  5422. }
  5423. return v;
  5424. }
  5425. function toggleMaximizeMangleModal() {
  5426. const win = document.getElementById('mangle-modal-window');
  5427. if (!win) return;
  5428. if (win.classList.contains('max-w-[720px]')) {
  5429. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5430. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5431. } else {
  5432. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5433. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5434. }
  5435. }
  5436. function syncMangleChainFromSelect() {
  5437. const sel = document.getElementById('mangle-modal-chain-select');
  5438. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5439. const customInput = document.getElementById('mangle-modal-custom-input');
  5440. const chainInput = document.getElementById('mangle-modal-chain');
  5441. if (!sel || !chainInput) return;
  5442. if (sel.value === '__custom__') {
  5443. if (customWrap) customWrap.classList.remove('hidden');
  5444. if (customInput) {
  5445. customInput.value = '';
  5446. customInput.focus();
  5447. }
  5448. chainInput.value = '';
  5449. } else {
  5450. if (customWrap) customWrap.classList.add('hidden');
  5451. chainInput.value = sel.value;
  5452. }
  5453. handleMangleChainChange();
  5454. }
  5455. function syncMangleCustomChainInput() {
  5456. const customInput = document.getElementById('mangle-modal-custom-input');
  5457. const chainInput = document.getElementById('mangle-modal-chain');
  5458. if (customInput && chainInput) {
  5459. chainInput.value = customInput.value.trim();
  5460. }
  5461. handleMangleChainChange();
  5462. }
  5463. function handleMangleChainChange() {
  5464. const chainInput = document.getElementById('mangle-modal-chain');
  5465. const rawChain = (chainInput?.value || 'prerouting').trim();
  5466. const chain = rawChain.toLowerCase();
  5467. const sel = document.getElementById('mangle-modal-chain-select');
  5468. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5469. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5470. sel.value = chain;
  5471. }
  5472. }
  5473. const hintEl = document.getElementById('mangle-chain-hint');
  5474. if (hintEl) {
  5475. if (chain === 'prerouting') {
  5476. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5477. } else if (chain === 'input') {
  5478. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5479. } else if (chain === 'forward') {
  5480. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5481. } else if (chain === 'output') {
  5482. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5483. } else if (chain === 'postrouting') {
  5484. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5485. } else {
  5486. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5487. }
  5488. }
  5489. const rowIn = document.getElementById('mangle-row-iniface');
  5490. const rowInList = document.getElementById('mangle-row-inifacelist');
  5491. const rowOut = document.getElementById('mangle-row-outiface');
  5492. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5493. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5494. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5495. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5496. if (chain === 'prerouting' || chain === 'input') {
  5497. if (rowIn) rowIn.classList.remove('hidden');
  5498. if (rowInList) rowInList.classList.remove('hidden');
  5499. if (rowOut) rowOut.classList.add('hidden');
  5500. if (rowOutList) rowOutList.classList.add('hidden');
  5501. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5502. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5503. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5504. } else if (chain === 'output' || chain === 'postrouting') {
  5505. if (rowIn) rowIn.classList.add('hidden');
  5506. if (rowInList) rowInList.classList.add('hidden');
  5507. if (rowOut) rowOut.classList.remove('hidden');
  5508. if (rowOutList) rowOutList.classList.remove('hidden');
  5509. if (rowInBridge) rowInBridge.classList.add('hidden');
  5510. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5511. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5512. } else {
  5513. if (rowIn) rowIn.classList.remove('hidden');
  5514. if (rowInList) rowInList.classList.remove('hidden');
  5515. if (rowOut) rowOut.classList.remove('hidden');
  5516. if (rowOutList) rowOutList.classList.remove('hidden');
  5517. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5518. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5519. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5520. }
  5521. checkMangleActionChainCompatibility();
  5522. toggleMangleActionFields();
  5523. }
  5524. function checkMangleActionChainCompatibility() {
  5525. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5526. const chain = rawChain.toLowerCase();
  5527. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5528. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5529. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5530. if (!warnBox || !warnMsg) return;
  5531. let msg = '';
  5532. if (action === 'set-priority' && chain !== 'postrouting') {
  5533. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5534. }
  5535. if (msg) {
  5536. warnMsg.textContent = msg;
  5537. warnBox.classList.remove('hidden');
  5538. } else {
  5539. warnBox.classList.add('hidden');
  5540. }
  5541. }
  5542. function toggleMangleActionFields() {
  5543. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5544. // Hide all dynamic rows first
  5545. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5546. const el = document.getElementById(`mangle-row-${id}`);
  5547. if (el) el.classList.add('hidden');
  5548. });
  5549. const jumpBox = document.getElementById('mangle-action-jump-box');
  5550. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5551. if (jumpBox) jumpBox.classList.add('hidden');
  5552. if (addrBox) addrBox.classList.add('hidden');
  5553. // Activate matching rows
  5554. if (act === 'mark-connection') {
  5555. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5556. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5557. } else if (act === 'mark-routing') {
  5558. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5559. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5560. } else if (act === 'mark-packet') {
  5561. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5562. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5563. } else if (act === 'change-mss') {
  5564. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5565. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5566. } else if (act === 'change-dscp') {
  5567. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5568. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5569. } else if (act === 'change-ttl') {
  5570. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5571. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5572. } else if (act === 'set-priority') {
  5573. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5574. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5575. } else if (act === 'route') {
  5576. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5577. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5578. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5579. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5580. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5581. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5582. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5583. } else if (act === 'jump') {
  5584. if (jumpBox) jumpBox.classList.remove('hidden');
  5585. } else if (act.includes('address-list') || act.includes('address list')) {
  5586. if (addrBox) addrBox.classList.remove('hidden');
  5587. }
  5588. if (act === 'log') {
  5589. const logEl = document.getElementById('mangle-modal-log');
  5590. if (logEl) logEl.checked = true;
  5591. toggleMangleField('logprefix', true);
  5592. }
  5593. checkMangleActionChainCompatibility();
  5594. }
  5595. function toggleMangleLogPrefix() {
  5596. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5597. toggleMangleField('logprefix', !!isLog);
  5598. }
  5599. const allMangleFieldKeys = [
  5600. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5601. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5602. 'routingmark', 'conntype', 'cs', 'natstate',
  5603. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5604. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5605. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5606. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5607. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5608. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5609. ];
  5610. function openAddMangleModal() {
  5611. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5612. switchMangleRuleTab('general');
  5613. const badge = document.getElementById('mangle-modal-badge');
  5614. if (badge) badge.innerText = 'New...';
  5615. document.getElementById('mangle-modal-id').value = '';
  5616. document.getElementById('mangle-modal-family').value = '4';
  5617. document.getElementById('mangle-modal-enabled').checked = true;
  5618. document.getElementById('mangle-modal-comment').value = '';
  5619. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5620. populateChainDropdown('mangle', 'prerouting');
  5621. handleMangleChainChange();
  5622. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5623. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5624. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5625. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5626. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5627. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5628. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5629. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5630. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5631. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5632. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5633. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5634. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5635. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5636. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5637. populateInterfaceSelect('mangle-val-iniface');
  5638. populateInterfaceSelect('mangle-val-outiface');
  5639. populateAddressListSelect('mangle-val-srclist');
  5640. populateAddressListSelect('mangle-val-dstlist');
  5641. populateGeoIPSelect('mangle-val-srcgeo');
  5642. populateGeoIPSelect('mangle-val-dstgeo');
  5643. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5644. resetMangleCounterDisplay();
  5645. toggleMangleActionFields();
  5646. document.getElementById('mangle-modal').classList.remove('hidden');
  5647. }
  5648. function openEditMangleModal(id) {
  5649. id = decodeURIComponent(id);
  5650. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5651. if (!r) return;
  5652. switchMangleRuleTab('general');
  5653. const badge = document.getElementById('mangle-modal-badge');
  5654. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5655. document.getElementById('mangle-modal-id').value = r.id;
  5656. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5657. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5658. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5659. const mangleChain = r.chain || 'prerouting';
  5660. document.getElementById('mangle-modal-chain').value = mangleChain;
  5661. populateChainDropdown('mangle', mangleChain);
  5662. handleMangleChainChange();
  5663. setFirewallActionSelection('mangle', r.action || 'accept');
  5664. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5665. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5666. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5667. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5668. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5669. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5670. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5671. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5672. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5673. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5674. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5675. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5676. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5677. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5678. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5679. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5680. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5681. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5682. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5683. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5684. setMangleFieldVal('src', r.src_address, true);
  5685. setMangleFieldVal('dst', r.dst_address, true);
  5686. setMangleFieldVal('srclist', r.src_address_list, true);
  5687. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5688. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5689. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5690. if (r.protocol && r.protocol !== 'all') {
  5691. setMangleFieldVal('proto', r.protocol, true);
  5692. } else {
  5693. toggleMangleField('proto', false);
  5694. }
  5695. setMangleFieldVal('sport', r.src_port, true);
  5696. setMangleFieldVal('dport', r.dst_port, true);
  5697. setMangleFieldVal('anyport', r.any_port, true);
  5698. setMangleFieldVal('iniface', r.in_interface, true);
  5699. setMangleFieldVal('outiface', r.out_interface, true);
  5700. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5701. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5702. setMangleFieldVal('pktmark', r.packet_mark, true);
  5703. setMangleFieldVal('connmark', r.connection_mark, true);
  5704. setMangleFieldVal('routingmark', r.routing_mark, true);
  5705. setMangleFieldVal('conntype', r.connection_type, false);
  5706. // Connection State
  5707. const states = r.connection_state || [];
  5708. if (states.length > 0) {
  5709. toggleMangleField('cs', true);
  5710. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5711. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5712. if (el) el.checked = states.includes(s);
  5713. });
  5714. } else {
  5715. toggleMangleField('cs', false);
  5716. }
  5717. // Connection NAT State
  5718. const natStates = r.connection_nat_state || [];
  5719. if (natStates.length > 0) {
  5720. toggleMangleField('natstate', true);
  5721. ['srcnat', 'dstnat'].forEach(s => {
  5722. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5723. if (el) el.checked = natStates.includes(s);
  5724. });
  5725. } else {
  5726. toggleMangleField('natstate', false);
  5727. }
  5728. // Advanced tab fields
  5729. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5730. setMangleFieldVal('content', r.content, false);
  5731. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5732. setMangleFieldVal('connrate', r.connection_rate, false);
  5733. setMangleFieldVal('pcc', r.pcc, false);
  5734. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5735. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5736. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5737. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5738. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5739. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5740. setMangleFieldVal('tlshost', r.tls_host, false);
  5741. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5742. setMangleFieldVal('priority', r.priority, false);
  5743. setMangleFieldVal('dscp', r.dscp, false);
  5744. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5745. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5746. setMangleFieldVal('pktsize', r.packet_size, false);
  5747. setMangleFieldVal('random', r.random, false);
  5748. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5749. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5750. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5751. setMangleFieldVal('ttl', r.ttl, false);
  5752. // Extra tab fields
  5753. setMangleFieldVal('nth', r.nth, false);
  5754. setMangleFieldVal('connlimit', r.connection_limit, false);
  5755. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5756. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5757. setMangleFieldVal('hotspot', r.hotspot, false);
  5758. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5759. setMangleFieldVal('limit', r.limit, false);
  5760. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5761. setMangleFieldVal('time', r.time, false);
  5762. setMangleFieldVal('psd', r.psd, false);
  5763. // Action fields
  5764. if (r.jump_target) {
  5765. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5766. if (jtEl) jtEl.value = r.jump_target;
  5767. }
  5768. if (r.address_list) {
  5769. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5770. if (alEl) alEl.value = r.address_list;
  5771. }
  5772. if (r.address_list_timeout) {
  5773. const toEl = document.getElementById('mangle-modal-action-timeout');
  5774. if (toEl) toEl.value = r.address_list_timeout;
  5775. }
  5776. setMangleFieldVal('logprefix', r.log_prefix, false);
  5777. // Statistics
  5778. const bEl = document.getElementById('mangle-stat-bytes');
  5779. const pEl = document.getElementById('mangle-stat-packets');
  5780. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5781. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5782. state.mangleLastBytes = r.bytes || 0;
  5783. state.mangleLastPackets = r.packets || 0;
  5784. state.mangleLastTimestamp = Date.now();
  5785. state.mangleStatRateHistory = new Array(30).fill(0);
  5786. state.mangleStatPktHistory = new Array(30).fill(0);
  5787. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5788. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5789. toggleMangleActionFields();
  5790. document.getElementById('mangle-modal').classList.remove('hidden');
  5791. }
  5792. function closeMangleModal() {
  5793. stopMangleStatPolling();
  5794. document.getElementById('mangle-modal').classList.add('hidden');
  5795. }
  5796. function copyMangleRule() {
  5797. document.getElementById('mangle-modal-id').value = '';
  5798. const badge = document.getElementById('mangle-modal-badge');
  5799. if (badge) badge.innerText = 'New...';
  5800. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5801. }
  5802. function resetMangleCounterDisplay() {
  5803. state.mangleStatRateHistory = new Array(30).fill(0);
  5804. state.mangleStatPktHistory = new Array(30).fill(0);
  5805. state.mangleLastBytes = 0;
  5806. state.mangleLastPackets = 0;
  5807. state.mangleLastTimestamp = Date.now();
  5808. const bEl = document.getElementById('mangle-stat-bytes');
  5809. const pEl = document.getElementById('mangle-stat-packets');
  5810. const rEl = document.getElementById('mangle-stat-rate');
  5811. const prEl = document.getElementById('mangle-stat-pktrate');
  5812. if (bEl) bEl.value = '0 B';
  5813. if (pEl) pEl.value = '0';
  5814. if (rEl) rEl.value = '0 bps';
  5815. if (prEl) prEl.value = '0 p/s';
  5816. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5817. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5818. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5819. }
  5820. async function applyMangleRule(closeAfter = false) {
  5821. const id = document.getElementById('mangle-modal-id').value;
  5822. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5823. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5824. const chainLower = chain.toLowerCase();
  5825. const action = document.getElementById('mangle-modal-action').value;
  5826. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5827. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5828. const src = getMangleFieldVal('src', true);
  5829. const dst = getMangleFieldVal('dst', true);
  5830. const srclist = getMangleFieldVal('srclist', true);
  5831. const dstlist = getMangleFieldVal('dstlist', true);
  5832. const srcgeo = getMangleFieldVal('srcgeo', true);
  5833. const dstgeo = getMangleFieldVal('dstgeo', true);
  5834. const proto = getMangleFieldVal('proto', true);
  5835. const sport = getMangleFieldVal('sport', true);
  5836. const dport = getMangleFieldVal('dport', true);
  5837. const anyport = getMangleFieldVal('anyport', true);
  5838. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5839. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5840. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5841. }
  5842. let iniface = getMangleFieldVal('iniface', true);
  5843. let outiface = getMangleFieldVal('outiface', true);
  5844. let inifacelist = getMangleFieldVal('inifacelist', true);
  5845. let outifacelist = getMangleFieldVal('outifacelist', true);
  5846. if (chainLower === 'prerouting' || chainLower === 'input') {
  5847. outiface = '';
  5848. outifacelist = '';
  5849. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5850. iniface = '';
  5851. inifacelist = '';
  5852. }
  5853. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5854. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5855. switchMangleRuleTab('general');
  5856. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5857. return;
  5858. }
  5859. const pktmark = getMangleFieldVal('pktmark', true);
  5860. const connmark = getMangleFieldVal('connmark', true);
  5861. const routingmark = getMangleFieldVal('routingmark', true);
  5862. const conntype = getMangleFieldVal('conntype', false);
  5863. const states = [];
  5864. const csBox = document.getElementById('mangle-field-cs');
  5865. if (csBox && !csBox.classList.contains('hidden')) {
  5866. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5867. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5868. });
  5869. }
  5870. const natStates = [];
  5871. const natBox = document.getElementById('mangle-field-natstate');
  5872. if (natBox && !natBox.classList.contains('hidden')) {
  5873. ['srcnat', 'dstnat'].forEach(s => {
  5874. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5875. });
  5876. }
  5877. const payload = {
  5878. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5879. id,
  5880. chain,
  5881. action,
  5882. protocol: proto || 'all',
  5883. src_address: src,
  5884. dst_address: dst,
  5885. src_port: sport,
  5886. dst_port: dport,
  5887. any_port: anyport,
  5888. in_interface: iniface,
  5889. out_interface: outiface,
  5890. in_interface_list: inifacelist,
  5891. out_interface_list: outifacelist,
  5892. packet_mark: pktmark,
  5893. connection_mark: connmark,
  5894. routing_mark: routingmark,
  5895. connection_type: conntype,
  5896. connection_state: states,
  5897. connection_nat_state: natStates,
  5898. src_address_list: srclist,
  5899. dst_address_list: dstlist,
  5900. src_geoip: srcgeo,
  5901. dst_geoip: dstgeo,
  5902. comment,
  5903. disabled: !enabled,
  5904. // Advanced tab
  5905. content: getMangleFieldVal('content', false),
  5906. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5907. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5908. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5909. ipsec_policy: getMangleFieldVal('ipsec', false),
  5910. dscp: getMangleFieldVal('dscp', false),
  5911. tcp_mss: getMangleFieldVal('tcpmss', false),
  5912. tos: document.getElementById('mangle-val-tos')?.value || '',
  5913. packet_size: getMangleFieldVal('pktsize', false),
  5914. random: getMangleFieldVal('random', false),
  5915. tcp_flags: getMangleFieldVal('tcpflags', false),
  5916. icmp_options: getMangleFieldVal('icmpoptions', false),
  5917. ttl: getMangleFieldVal('ttl', false),
  5918. // Extra tab
  5919. nth: getMangleFieldVal('nth', false),
  5920. connection_limit: getMangleFieldVal('connlimit', false),
  5921. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5922. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5923. ip_fragment: getMangleFieldVal('ipfragment', false),
  5924. limit: getMangleFieldVal('limit', false),
  5925. time: getMangleFieldVal('time', false),
  5926. // Action tab
  5927. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5928. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5929. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5930. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5931. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5932. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5933. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5934. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5935. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5936. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5937. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5938. log: document.getElementById('mangle-modal-log')?.checked || false,
  5939. log_prefix: getMangleFieldVal('logprefix', false)
  5940. };
  5941. try {
  5942. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5943. method: 'POST',
  5944. headers: { 'Content-Type': 'application/json' },
  5945. body: JSON.stringify(payload)
  5946. });
  5947. if (res.ok) {
  5948. const data = await res.json();
  5949. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5950. loadFirewall(false);
  5951. if (closeAfter) {
  5952. closeMangleModal();
  5953. } else {
  5954. if (data.id) {
  5955. document.getElementById('mangle-modal-id').value = data.id;
  5956. const badge = document.getElementById('mangle-modal-badge');
  5957. if (badge) badge.innerText = `#${data.id}`;
  5958. }
  5959. }
  5960. } else {
  5961. const err = await res.json();
  5962. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5963. }
  5964. } catch (err) {
  5965. showToast('Error', err.message, 'error');
  5966. }
  5967. }
  5968. function submitSaveMangleRule(e) {
  5969. if (e && e.preventDefault) e.preventDefault();
  5970. return applyMangleRule(true);
  5971. }
  5972. function startMangleStatPolling() {
  5973. stopMangleStatPolling();
  5974. pollMangleRuleStats();
  5975. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5976. }
  5977. function stopMangleStatPolling() {
  5978. if (state.mangleStatInterval) {
  5979. clearInterval(state.mangleStatInterval);
  5980. state.mangleStatInterval = null;
  5981. }
  5982. }
  5983. async function pollMangleRuleStats() {
  5984. const id = document.getElementById('mangle-modal-id')?.value;
  5985. if (!id) {
  5986. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5987. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5988. return;
  5989. }
  5990. try {
  5991. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5992. if (!res.ok) return;
  5993. const rules = await res.json();
  5994. const r = rules.find(x => x.id === id);
  5995. if (!r) return;
  5996. const now = Date.now();
  5997. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5998. state.mangleLastTimestamp = now;
  5999. const curBytes = r.bytes || 0;
  6000. const curPackets = r.packets || 0;
  6001. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6002. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6003. state.mangleLastBytes = curBytes;
  6004. state.mangleLastPackets = curPackets;
  6005. const rateBps = Math.round((deltaBytes * 8) / dt);
  6006. const ratePkt = Math.round(deltaPkts / dt);
  6007. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6008. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6009. state.mangleStatRateHistory.push(rateBps);
  6010. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6011. state.mangleStatPktHistory.push(ratePkt);
  6012. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6013. const bEl = document.getElementById('mangle-stat-bytes');
  6014. const pEl = document.getElementById('mangle-stat-packets');
  6015. const rEl = document.getElementById('mangle-stat-rate');
  6016. const prEl = document.getElementById('mangle-stat-pktrate');
  6017. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6018. if (pEl) pEl.value = curPackets.toLocaleString();
  6019. if (rEl) rEl.value = formatBps(rateBps);
  6020. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6021. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6022. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6023. } catch (e) {
  6024. console.error('Error polling Mangle rule stats', e);
  6025. }
  6026. }
  6027. async function moveMangleRule(id, dir) {
  6028. id = decodeURIComponent(id);
  6029. try {
  6030. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6031. method: 'POST',
  6032. headers: { 'Content-Type': 'application/json' },
  6033. body: JSON.stringify({ direction: dir })
  6034. });
  6035. if (!res.ok) throw new Error(await responseError(res));
  6036. await loadFirewall(false);
  6037. } catch (err) {
  6038. showToast('Error', err.message, 'error');
  6039. }
  6040. }
  6041. async function toggleMangleRuleState(id, disabled) {
  6042. id = decodeURIComponent(id);
  6043. try {
  6044. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6045. method: 'POST',
  6046. headers: { 'Content-Type': 'application/json' },
  6047. body: JSON.stringify({ disabled })
  6048. });
  6049. if (!res.ok) throw new Error(await responseError(res));
  6050. await loadFirewall(false);
  6051. } catch (err) {
  6052. showToast('Error', err.message, 'error');
  6053. }
  6054. }
  6055. async function deleteMangleRule(id) {
  6056. id = decodeURIComponent(id);
  6057. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6058. try {
  6059. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6060. if (!res.ok) throw new Error(await responseError(res));
  6061. {
  6062. showToast('Deleted', 'Mangle rule removed', 'success');
  6063. loadFirewall(false);
  6064. }
  6065. } catch (err) {
  6066. showToast('Error', err.message, 'error');
  6067. }
  6068. }
  6069. // ----------------- Address Lists -----------------
  6070. function renderAddressLists() {
  6071. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6072. const tbody = document.getElementById('addrlist-table-body');
  6073. const empty = document.getElementById('addrlist-empty');
  6074. if (!tbody) return;
  6075. tbody.innerHTML = '';
  6076. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6077. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6078. // Update filter select
  6079. const sel = document.getElementById('addrlist-filter-name');
  6080. if (sel) {
  6081. const cur = sel.value;
  6082. sel.innerHTML = '<option value="">All Lists</option>';
  6083. const set = new Set((state.addressLists || []).map(a => a.name));
  6084. set.forEach(n => {
  6085. const opt = document.createElement('option');
  6086. opt.value = n;
  6087. opt.innerText = n;
  6088. if (n === cur) opt.selected = true;
  6089. sel.appendChild(opt);
  6090. });
  6091. }
  6092. if (entries.length === 0) {
  6093. empty?.classList.remove('hidden');
  6094. return;
  6095. }
  6096. empty?.classList.add('hidden');
  6097. entries.forEach((raw, idx) => {
  6098. const e = safeFirewallRow(raw);
  6099. const tr = document.createElement('tr');
  6100. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6101. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6102. tr.innerHTML = `
  6103. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6104. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400 font-bold">✓</span>'}</td>
  6105. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6106. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6107. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.dynamic ? 'Dynamic · '+(e.timeout ? e.timeout+'s remaining' : 'no expiry') : e.comment || '-'}</td>
  6108. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6109. ${e.dynamic ? '' : ` <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  6110. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6111. `}
  6112. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6113. </td>
  6114. `;
  6115. tbody.appendChild(tr);
  6116. });
  6117. populateCommonAddrListDatalist();
  6118. }
  6119. function openAddAddrListModal() {
  6120. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6121. document.getElementById('addrlist-modal-id').value = '';
  6122. document.getElementById('addrlist-modal-name').value = '';
  6123. document.getElementById('addrlist-modal-addr').value = '';
  6124. document.getElementById('addrlist-modal-comment').value = '';
  6125. document.getElementById('addrlist-modal-disabled').checked = false;
  6126. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6127. if (submitBtn) submitBtn.innerText = 'Add to List';
  6128. document.getElementById('addrlist-modal').classList.remove('hidden');
  6129. }
  6130. function openEditAddrListModal(id) {
  6131. id = decodeURIComponent(id);
  6132. const e = (state.addressLists || []).find(item => item.id === id);
  6133. if (!e) return;
  6134. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6135. document.getElementById('addrlist-modal-id').value = e.id;
  6136. document.getElementById('addrlist-modal-name').value = e.name;
  6137. document.getElementById('addrlist-modal-addr').value = e.address;
  6138. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6139. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6140. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6141. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6142. document.getElementById('addrlist-modal').classList.remove('hidden');
  6143. }
  6144. function closeAddrListModal() {
  6145. document.getElementById('addrlist-modal').classList.add('hidden');
  6146. }
  6147. async function submitSaveAddrList(e) {
  6148. e.preventDefault();
  6149. const id = document.getElementById('addrlist-modal-id').value;
  6150. const name = document.getElementById('addrlist-modal-name').value.trim();
  6151. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6152. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6153. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6154. try {
  6155. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6156. method: 'POST',
  6157. headers: { 'Content-Type': 'application/json' },
  6158. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6159. });
  6160. if (res.ok) {
  6161. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6162. closeAddrListModal();
  6163. loadFirewall(false);
  6164. } else {
  6165. const err = await res.json();
  6166. showToast('Error', err.message || 'Failed to save address list', 'error');
  6167. }
  6168. } catch (err) {
  6169. showToast('Error', err.message, 'error');
  6170. }
  6171. }
  6172. async function toggleAddrListState(id, disabled) {
  6173. id = decodeURIComponent(id);
  6174. try {
  6175. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6176. method: 'POST',
  6177. headers: { 'Content-Type': 'application/json' },
  6178. body: JSON.stringify({ disabled })
  6179. });
  6180. if (res.ok) {
  6181. loadFirewall(false);
  6182. }
  6183. } catch (err) {
  6184. showToast('Error', err.message, 'error');
  6185. }
  6186. }
  6187. async function deleteAddrList(id) {
  6188. id = decodeURIComponent(id);
  6189. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6190. try {
  6191. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6192. if (res.ok) {
  6193. showToast('Deleted', 'Address list item removed', 'info');
  6194. loadFirewall(false);
  6195. }
  6196. } catch (err) {
  6197. showToast('Error', err.message, 'error');
  6198. }
  6199. }
  6200. // ----------------- Geo-Location IP Management -----------------
  6201. async function loadGeoIP() {
  6202. try {
  6203. const [statusRes, countriesRes] = await Promise.all([
  6204. fetch(`${API_BASE}/firewall/geoip/status`),
  6205. fetch(`${API_BASE}/firewall/geoip/countries`)
  6206. ]);
  6207. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6208. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6209. updateGeoHeader();
  6210. renderGeoCountries();
  6211. } catch (err) {
  6212. console.error('Failed to load GeoIP:', err);
  6213. }
  6214. }
  6215. function getGeoUsageMap() {
  6216. const usage = {};
  6217. const checkRule = (r, type) => {
  6218. ['src_geoip', 'dst_geoip'].forEach(field => {
  6219. let val = (r && r[field]) || '';
  6220. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6221. if (code) {
  6222. if (!usage[code]) usage[code] = [];
  6223. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6224. if (!usage[code].includes(label)) usage[code].push(label);
  6225. }
  6226. });
  6227. };
  6228. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6229. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6230. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6231. return usage;
  6232. }
  6233. function updateGeoHeader() {
  6234. const s = state.geoStatus || {};
  6235. const statusBadge = document.getElementById('geo-status-badge');
  6236. if (statusBadge) {
  6237. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6238. statusBadge.className = s.auto_update
  6239. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6240. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6241. }
  6242. const intervalLabel = document.getElementById('geo-interval-label');
  6243. if (intervalLabel) {
  6244. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6245. }
  6246. const usageMap = getGeoUsageMap();
  6247. const inUseCount = Object.keys(usageMap).length;
  6248. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6249. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6250. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6251. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6252. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6253. if (lastSyncEl) {
  6254. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6255. const d = new Date(s.last_updated);
  6256. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6257. } else {
  6258. lastSyncEl.innerText = 'Never (Sync Pending)';
  6259. }
  6260. }
  6261. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6262. if (nextSyncEl) {
  6263. if (s.next_update && !s.next_update.startsWith('0001')) {
  6264. const d = new Date(s.next_update);
  6265. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6266. } else {
  6267. nextSyncEl.innerText = '-';
  6268. }
  6269. }
  6270. const badge = document.getElementById('fw-badge-geo');
  6271. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6272. }
  6273. function renderGeoCountries() {
  6274. const tbody = document.getElementById('geo-table-body');
  6275. const empty = document.getElementById('geo-empty');
  6276. if (!tbody) return;
  6277. tbody.innerHTML = '';
  6278. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6279. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6280. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6281. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6282. const usageMap = getGeoUsageMap();
  6283. const countries = (state.geoCountries || []).filter(c => {
  6284. const isUsed = !!usageMap[c.code];
  6285. if (inUseOnly && !isUsed) return false;
  6286. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6287. if (continent && c.continent !== continent) return false;
  6288. if (q) {
  6289. const matchCode = c.code.toLowerCase().includes(q);
  6290. const matchName = c.name.toLowerCase().includes(q);
  6291. if (!matchCode && !matchName) return false;
  6292. }
  6293. return true;
  6294. });
  6295. if (countries.length === 0) {
  6296. empty?.classList.remove('hidden');
  6297. return;
  6298. }
  6299. empty?.classList.add('hidden');
  6300. countries.forEach(c => {
  6301. const tr = document.createElement('tr');
  6302. const isUsed = !!usageMap[c.code];
  6303. const rulesUsing = usageMap[c.code] || [];
  6304. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6305. let statusHtml = '';
  6306. if (isUsed) {
  6307. statusHtml = `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  6308. } else if (c.subnet_count > 0) {
  6309. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  6310. } else {
  6311. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6312. }
  6313. tr.innerHTML = `
  6314. <td class="py-2.5 px-3 text-center">
  6315. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  6316. ${c.code}
  6317. </span>
  6318. </td>
  6319. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6320. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6321. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6322. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6323. </td>
  6324. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6325. <td class="py-2.5 px-3">
  6326. ${statusHtml}
  6327. </td>
  6328. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6329. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  6330. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6331. </td>
  6332. `;
  6333. tbody.appendChild(tr);
  6334. });
  6335. }
  6336. function quickFilterGeo(preset) {
  6337. const searchInput = document.getElementById('geo-search-input');
  6338. const continentSel = document.getElementById('geo-continent-filter');
  6339. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6340. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6341. if (searchInput) searchInput.value = '';
  6342. if (continentSel) continentSel.value = '';
  6343. if (inUseCheck) inUseCheck.checked = false;
  6344. if (cachedCheck) cachedCheck.checked = false;
  6345. if (preset === 'GR') {
  6346. if (searchInput) searchInput.value = 'Greece';
  6347. } else if (preset === 'Europe') {
  6348. if (continentSel) continentSel.value = 'Europe';
  6349. } else if (preset === 'HIGHRISK') {
  6350. if (searchInput) searchInput.value = 'China';
  6351. }
  6352. renderGeoCountries();
  6353. }
  6354. async function toggleGeoCountry(code, enabled) {
  6355. try {
  6356. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6357. method: 'POST',
  6358. headers: { 'Content-Type': 'application/json' },
  6359. body: JSON.stringify({ enabled })
  6360. });
  6361. if (res.ok) {
  6362. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6363. loadGeoIP();
  6364. } else {
  6365. const err = await res.json();
  6366. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6367. }
  6368. } catch (err) {
  6369. showToast('Error', err.message, 'error');
  6370. }
  6371. }
  6372. async function updateGeoCountry(code) {
  6373. try {
  6374. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6375. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6376. if (res.ok) {
  6377. const data = await res.json();
  6378. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6379. loadGeoIP();
  6380. } else {
  6381. const err = await res.json();
  6382. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6383. }
  6384. } catch (err) {
  6385. showToast('Error', err.message, 'error');
  6386. }
  6387. }
  6388. async function triggerGeoUpdateNow() {
  6389. const spinner = document.getElementById('geo-update-spinner');
  6390. if (spinner) spinner.classList.remove('hidden');
  6391. try {
  6392. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6393. if (res.ok) {
  6394. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6395. setTimeout(() => {
  6396. loadGeoIP();
  6397. if (spinner) spinner.classList.add('hidden');
  6398. }, 2500);
  6399. } else {
  6400. const err = await res.json();
  6401. showToast('Notice', err.message || 'Update in progress', 'info');
  6402. if (spinner) spinner.classList.add('hidden');
  6403. }
  6404. } catch (err) {
  6405. showToast('Error', err.message, 'error');
  6406. if (spinner) spinner.classList.add('hidden');
  6407. }
  6408. }
  6409. async function applyGeoPreset(preset) {
  6410. try {
  6411. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6412. method: 'POST',
  6413. headers: { 'Content-Type': 'application/json' },
  6414. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6415. });
  6416. if (res.ok) {
  6417. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6418. loadGeoIP();
  6419. }
  6420. } catch (err) {
  6421. showToast('Error', err.message, 'error');
  6422. }
  6423. }
  6424. function openGeoIntervalModal() {
  6425. const s = state.geoStatus || {};
  6426. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6427. const sel = document.getElementById('geo-cfg-interval');
  6428. const customBox = document.getElementById('geo-cfg-custom-box');
  6429. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6430. const curHours = s.interval_hours || 24;
  6431. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6432. if (matchOption) {
  6433. sel.value = String(curHours);
  6434. customBox.classList.add('hidden');
  6435. } else {
  6436. sel.value = 'custom';
  6437. customHoursInput.value = curHours;
  6438. customBox.classList.remove('hidden');
  6439. }
  6440. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6441. }
  6442. function closeGeoIntervalModal() {
  6443. document.getElementById('geo-interval-modal').classList.add('hidden');
  6444. }
  6445. function toggleCustomGeoInterval() {
  6446. const val = document.getElementById('geo-cfg-interval').value;
  6447. const customBox = document.getElementById('geo-cfg-custom-box');
  6448. if (val === 'custom') {
  6449. customBox.classList.remove('hidden');
  6450. } else {
  6451. customBox.classList.add('hidden');
  6452. }
  6453. }
  6454. async function submitGeoIntervalSettings(e) {
  6455. e.preventDefault();
  6456. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6457. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6458. let hours = 24;
  6459. if (intervalVal === 'custom') {
  6460. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6461. } else {
  6462. hours = parseInt(intervalVal, 10) || 24;
  6463. }
  6464. try {
  6465. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6466. method: 'POST',
  6467. headers: { 'Content-Type': 'application/json' },
  6468. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6469. });
  6470. if (res.ok) {
  6471. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6472. closeGeoIntervalModal();
  6473. loadGeoIP();
  6474. } else {
  6475. const err = await res.json();
  6476. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6477. }
  6478. } catch (err) {
  6479. showToast('Error', err.message, 'error');
  6480. }
  6481. }
  6482. async function viewGeoSubnets(code, name) {
  6483. if (!name) {
  6484. const found = (state.geoCountries || []).find(x => x.code === code);
  6485. name = found ? found.name : code;
  6486. }
  6487. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6488. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6489. const listEl = document.getElementById('geo-subnets-list');
  6490. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6491. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6492. try {
  6493. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6494. if (res.ok) {
  6495. const data = await res.json();
  6496. const subnets = data.subnets || [];
  6497. if (subnets.length === 0) {
  6498. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6499. } else {
  6500. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6501. }
  6502. } else {
  6503. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6504. }
  6505. } catch (err) {
  6506. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6507. }
  6508. }
  6509. function closeGeoSubnetsModal() {
  6510. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6511. }
  6512. // ----------------- Active Connections Tracking -----------------
  6513. async function loadConnections() {
  6514. try {
  6515. const res = await fetch(`${API_BASE}/firewall/connections`);
  6516. const data = await res.json();
  6517. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6518. state.connections = Array.isArray(data) ? data : [];
  6519. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6520. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6521. renderConnections();
  6522. } catch (err) {
  6523. console.error('Failed to load connections:', err);
  6524. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6525. }
  6526. }
  6527. function renderConnections() {
  6528. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6529. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6530. const tbody = document.getElementById('conns-table-body');
  6531. const empty = document.getElementById('conns-empty');
  6532. if (!tbody) return;
  6533. tbody.innerHTML = '';
  6534. const conns = (state.connections || []).filter(c => {
  6535. if (protoFilter && c.protocol !== protoFilter) return false;
  6536. if (search) {
  6537. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6538. if (!line.includes(search)) return false;
  6539. }
  6540. return true;
  6541. });
  6542. if (conns.length === 0) {
  6543. empty?.classList.remove('hidden');
  6544. return;
  6545. }
  6546. empty?.classList.add('hidden');
  6547. conns.slice(0, 150).forEach(c => {
  6548. const tr = document.createElement('tr');
  6549. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6550. let stateColor = 'text-slate-400';
  6551. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6552. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6553. tr.innerHTML = `
  6554. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6555. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6556. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6557. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  6558. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  6559. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6560. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6561. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6562. <td class="py-2.5 px-3 text-right font-sans">
  6563. ${['TCP','UDP','SCTP','DCCP','ICMP','ICMPV6'].includes(c.protocol) ? ` <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port}, ${c.ip_version || 4}, ${c.zone || 0}, ${c.icmp_id ?? 'null'}, ${c.icmp_type ?? 'null'}, ${c.icmp_code ?? 'null'})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>` : ''}
  6564. </td>
  6565. `;
  6566. tbody.appendChild(tr);
  6567. });
  6568. }
  6569. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6570. try {
  6571. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6572. method: 'POST',
  6573. headers: { 'Content-Type': 'application/json' },
  6574. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6575. });
  6576. if (res.ok) {
  6577. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6578. loadConnections();
  6579. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6580. } catch (err) {
  6581. showToast('Error', err.message, 'error');
  6582. }
  6583. }
  6584. async function resetFirewallCounters() {
  6585. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6586. try {
  6587. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6588. if (res.ok) {
  6589. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6590. loadFirewall(false);
  6591. }
  6592. } catch (err) {
  6593. showToast('Error', err.message, 'error');
  6594. }
  6595. }
  6596. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6597. function switchRoutesSubTab(tab) {
  6598. state.routesSubTab = tab;
  6599. const tabs = ['routes', 'rules', 'tables'];
  6600. tabs.forEach(t => {
  6601. const panel = document.getElementById(`routes-subtab-${t}`);
  6602. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6603. if (panel) {
  6604. if (t === tab) panel.classList.remove('hidden');
  6605. else panel.classList.add('hidden');
  6606. }
  6607. if (btn) {
  6608. if (t === tab) {
  6609. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  6610. } else {
  6611. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  6612. }
  6613. }
  6614. });
  6615. setTimeout(initTableSorting, 50);
  6616. }
  6617. async function loadRoutes() {
  6618. try {
  6619. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6620. fetch(`${API_BASE}/routes`),
  6621. fetch(`${API_BASE}/routing/rules`),
  6622. fetch(`${API_BASE}/routing/tables`)
  6623. ]);
  6624. if (routesRes.ok) state.routes = await routesRes.json();
  6625. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6626. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6627. const bRoutes = document.getElementById('routes-badge-routes');
  6628. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6629. const showSystem = document.getElementById('prule-show-system')?.checked;
  6630. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6631. const bRules = document.getElementById('routes-badge-rules');
  6632. if (bRules) bRules.innerText = userRules.length;
  6633. const bTables = document.getElementById('routes-badge-tables');
  6634. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6635. const bRoutesCount = document.getElementById('badge-routes-count');
  6636. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6637. renderRoutesList();
  6638. renderPolicyRules();
  6639. renderRoutingTables();
  6640. } catch (err) {
  6641. console.error('Failed to load routing:', err);
  6642. }
  6643. }
  6644. function getRouteProtocolBadge(proto) {
  6645. const p = (proto || 'static').toLowerCase();
  6646. switch (p) {
  6647. case 'bgp':
  6648. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  6649. case 'ibgp':
  6650. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  6651. case 'ospf':
  6652. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  6653. case 'rip':
  6654. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  6655. case 'static':
  6656. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  6657. case 'connected':
  6658. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  6659. case 'dhcp':
  6660. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  6661. case 'multicast':
  6662. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  6663. default:
  6664. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  6665. }
  6666. }
  6667. function renderRoutesList() {
  6668. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6669. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6670. const tbody = document.getElementById('routes-table-body');
  6671. const empty = document.getElementById('routes-empty');
  6672. if (!tbody) return;
  6673. // Update table filter select
  6674. const sel = document.getElementById('routes-filter-table');
  6675. if (sel) {
  6676. const cur = sel.value;
  6677. sel.innerHTML = '<option value="">All Tables</option>';
  6678. (state.routingTables || []).forEach(t => {
  6679. const opt = document.createElement('option');
  6680. opt.value = t.name;
  6681. opt.innerText = t.name;
  6682. if (t.name === cur) opt.selected = true;
  6683. sel.appendChild(opt);
  6684. });
  6685. }
  6686. const routes = (state.routes || []).filter(r => {
  6687. if (tableFilter && r.routing_table !== tableFilter) return false;
  6688. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6689. if (typeFilter === 'multicast' && !r.multicast) return false;
  6690. if (typeFilter === 'static' && !r.static) return false;
  6691. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6692. if (typeFilter === 'connected' && !r.connect) return false;
  6693. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6694. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6695. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6696. return true;
  6697. });
  6698. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6699. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6700. let summaryText = `${routes.length} Routes`;
  6701. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6702. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6703. const badgeEl = document.getElementById('routes-count-badge');
  6704. if (badgeEl) badgeEl.innerText = summaryText;
  6705. if (routes.length === 0) {
  6706. empty?.classList.remove('hidden');
  6707. tbody.innerHTML = '';
  6708. return;
  6709. }
  6710. empty?.classList.add('hidden');
  6711. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6712. if (tbody.dataset.sig === sig) {
  6713. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6714. }
  6715. tbody.dataset.sig = sig;
  6716. tbody.innerHTML = '';
  6717. routes.forEach(r => {
  6718. const tr = document.createElement('tr');
  6719. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6720. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6721. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6722. let flags = '';
  6723. if (r.dynamic) flags += 'D';
  6724. if (r.active) flags += 'A';
  6725. if (r.connect) flags += 'C';
  6726. if (r.static) flags += 'S';
  6727. if (r.ecmp) flags += 'E';
  6728. if (r.multicast) flags += 'M';
  6729. if (r.disabled) flags += 'X';
  6730. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6731. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6732. if (r.check_gateway === 'internet') {
  6733. if (r.health_status === 'online') {
  6734. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6735. healthCell = `
  6736. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  6737. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6738. <span>Internet OK (${ms}ms)</span>
  6739. </span>
  6740. `;
  6741. } else if (r.health_status === 'offline') {
  6742. healthCell = `
  6743. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  6744. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6745. <span>Internet Down</span>
  6746. </span>
  6747. `;
  6748. } else {
  6749. healthCell = `
  6750. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  6751. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6752. <span>Checking...</span>
  6753. </span>
  6754. `;
  6755. }
  6756. } else if (r.check_gateway === 'ping') {
  6757. if (r.health_status === 'online') {
  6758. healthCell = `
  6759. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  6760. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6761. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6762. </span>
  6763. `;
  6764. } else if (r.health_status === 'offline') {
  6765. healthCell = `
  6766. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  6767. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6768. <span>Gateway Dead</span>
  6769. </span>
  6770. `;
  6771. }
  6772. }
  6773. const flagDescriptions = [];
  6774. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6775. if (r.active) flagDescriptions.push('Active (A)');
  6776. if (r.connect) flagDescriptions.push('Connected (C)');
  6777. if (r.static) flagDescriptions.push('Static (S)');
  6778. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6779. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6780. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6781. tr.innerHTML = `
  6782. <td class="py-2.5 px-3 text-center">
  6783. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6784. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  6785. }" title="Flags: ${flagDescriptions.join(', ')}">
  6786. ${flags || '-'}
  6787. </span>
  6788. </td>
  6789. <td class="py-2.5 px-3">
  6790. <div class="flex items-center gap-1.5 flex-wrap">
  6791. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6792. ${r.ecmp ? `
  6793. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  6794. <span>⚡ ECMP</span>
  6795. </span>
  6796. ` : ''}
  6797. ${r.multicast ? `
  6798. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  6799. <span>IGMP</span>
  6800. </span>
  6801. ` : ''}
  6802. </div>
  6803. </td>
  6804. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6805. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  6806. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6807. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6808. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6809. <td class="py-2.5 px-3">${healthCell}</td>
  6810. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6811. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6812. ${r.static ? `
  6813. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  6814. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6815. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6816. ` : `
  6817. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6818. `}
  6819. </td>
  6820. `;
  6821. tbody.appendChild(tr);
  6822. });
  6823. }
  6824. function openAddRouteModal() {
  6825. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6826. document.getElementById('route-modal-id').value = '';
  6827. document.getElementById('route-modal-old-dst').value = '';
  6828. document.getElementById('route-modal-old-gw').value = '';
  6829. document.getElementById('route-modal-old-distance').value = '';
  6830. document.getElementById('route-modal-old-table').value = '';
  6831. document.getElementById('route-modal-old-iface').value = '';
  6832. const dstInput = document.getElementById('route-modal-dst');
  6833. const gwInput = document.getElementById('route-modal-gw');
  6834. const distInput = document.getElementById('route-modal-distance');
  6835. const ifaceSelect = document.getElementById('route-modal-iface');
  6836. const tableSelect = document.getElementById('route-modal-table');
  6837. const commentInput = document.getElementById('route-modal-comment');
  6838. const disCheck = document.getElementById('route-modal-disabled');
  6839. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6840. dstInput.disabled = false;
  6841. dstInput.value = '0.0.0.0/0';
  6842. gwInput.disabled = false;
  6843. gwInput.value = '';
  6844. distInput.disabled = false;
  6845. distInput.value = '1';
  6846. ifaceSelect.disabled = false;
  6847. tableSelect.disabled = false;
  6848. commentInput.disabled = false;
  6849. commentInput.value = '';
  6850. disCheck.disabled = false;
  6851. disCheck.checked = false;
  6852. if (saveBtn) saveBtn.classList.remove('hidden');
  6853. const checkGw = document.getElementById('route-modal-check-gw');
  6854. if (checkGw) checkGw.value = 'internet';
  6855. const checkTarget = document.getElementById('route-modal-check-target');
  6856. if (checkTarget) checkTarget.value = '1.1.1.1';
  6857. const checkInterval = document.getElementById('route-modal-check-interval');
  6858. if (checkInterval) checkInterval.value = '5';
  6859. const checkThresh = document.getElementById('route-modal-check-threshold');
  6860. if (checkThresh) checkThresh.value = '3';
  6861. toggleRouteCheckModeUI();
  6862. populateInterfaceSelect('route-modal-iface');
  6863. // Populate tables
  6864. tableSelect.innerHTML = '';
  6865. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6866. const opt = document.createElement('option');
  6867. opt.value = t.name;
  6868. opt.innerText = t.name;
  6869. if (t.name === 'main') opt.selected = true;
  6870. tableSelect.appendChild(opt);
  6871. });
  6872. document.getElementById('route-modal').classList.remove('hidden');
  6873. }
  6874. function openEditRouteModal(id) {
  6875. const r = (state.routes || []).find(route => route.id === id);
  6876. if (!r) return;
  6877. const isStatic = !!r.static;
  6878. document.getElementById('route-modal-title').innerText = isStatic
  6879. ? `Edit Route: ${r.dst_address}`
  6880. : `Route Properties (Read Only): ${r.dst_address}`;
  6881. document.getElementById('route-modal-id').value = r.id;
  6882. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6883. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6884. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6885. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6886. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6887. const dstInput = document.getElementById('route-modal-dst');
  6888. const gwInput = document.getElementById('route-modal-gw');
  6889. const distInput = document.getElementById('route-modal-distance');
  6890. const ifaceSelect = document.getElementById('route-modal-iface');
  6891. const tableSelect = document.getElementById('route-modal-table');
  6892. const commentInput = document.getElementById('route-modal-comment');
  6893. const disCheck = document.getElementById('route-modal-disabled');
  6894. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6895. dstInput.value = r.dst_address;
  6896. gwInput.value = r.gateway || '';
  6897. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6898. commentInput.value = r.comment || '';
  6899. disCheck.checked = !!r.disabled;
  6900. const checkGw = document.getElementById('route-modal-check-gw');
  6901. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6902. const checkTarget = document.getElementById('route-modal-check-target');
  6903. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6904. const checkInterval = document.getElementById('route-modal-check-interval');
  6905. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6906. const checkThresh = document.getElementById('route-modal-check-threshold');
  6907. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6908. toggleRouteCheckModeUI();
  6909. dstInput.disabled = !isStatic;
  6910. gwInput.disabled = !isStatic;
  6911. distInput.disabled = !isStatic;
  6912. ifaceSelect.disabled = !isStatic;
  6913. tableSelect.disabled = !isStatic;
  6914. commentInput.disabled = !isStatic;
  6915. disCheck.disabled = !isStatic;
  6916. if (checkGw) checkGw.disabled = !isStatic;
  6917. if (checkTarget) checkTarget.disabled = !isStatic;
  6918. if (checkInterval) checkInterval.disabled = !isStatic;
  6919. if (checkThresh) checkThresh.disabled = !isStatic;
  6920. if (saveBtn) {
  6921. if (isStatic) {
  6922. saveBtn.classList.remove('hidden');
  6923. } else {
  6924. saveBtn.classList.add('hidden');
  6925. }
  6926. }
  6927. populateInterfaceSelect('route-modal-iface', r.interface);
  6928. tableSelect.innerHTML = '';
  6929. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6930. const opt = document.createElement('option');
  6931. opt.value = t.name;
  6932. opt.innerText = t.name;
  6933. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6934. tableSelect.appendChild(opt);
  6935. });
  6936. document.getElementById('route-modal').classList.remove('hidden');
  6937. }
  6938. function closeRouteModal() {
  6939. document.getElementById('route-modal').classList.add('hidden');
  6940. }
  6941. function setRouteCheckTarget(ip) {
  6942. const inp = document.getElementById('route-modal-check-target');
  6943. if (inp) inp.value = ip;
  6944. }
  6945. function toggleRouteCheckModeUI() {
  6946. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6947. const targetRow = document.getElementById('route-row-check-target');
  6948. const paramsRow = document.getElementById('route-row-check-params');
  6949. if (mode === 'none') {
  6950. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6951. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6952. } else if (mode === 'ping') {
  6953. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6954. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6955. } else { // internet
  6956. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6957. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6958. }
  6959. }
  6960. async function submitSaveRoute(e) {
  6961. e.preventDefault();
  6962. const id = document.getElementById('route-modal-id').value;
  6963. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6964. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6965. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6966. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6967. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6968. const dst = document.getElementById('route-modal-dst').value.trim();
  6969. const gw = document.getElementById('route-modal-gw').value.trim();
  6970. const table = document.getElementById('route-modal-table').value;
  6971. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6972. const iface = document.getElementById('route-modal-iface').value;
  6973. const comment = document.getElementById('route-modal-comment').value.trim();
  6974. const disabled = document.getElementById('route-modal-disabled').checked;
  6975. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6976. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6977. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6978. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6979. if (!dst) {
  6980. showToast('Error', 'Destination address is required', 'error');
  6981. return;
  6982. }
  6983. if (!gw && !iface) {
  6984. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6985. return;
  6986. }
  6987. const payload = {
  6988. id,
  6989. old_dst_address: oldDst,
  6990. old_gateway: oldGw,
  6991. old_routing_table: oldTable,
  6992. old_interface: oldIface,
  6993. dst_address: dst,
  6994. gateway: gw || iface,
  6995. routing_table: table,
  6996. distance,
  6997. interface: iface,
  6998. comment,
  6999. disabled,
  7000. check_gateway,
  7001. check_target,
  7002. check_interval,
  7003. check_threshold
  7004. };
  7005. if (oldDistStr !== undefined && oldDistStr !== '') {
  7006. payload.old_distance = parseInt(oldDistStr, 10);
  7007. }
  7008. try {
  7009. const res = await fetch(`${API_BASE}/routes`, {
  7010. method: 'POST',
  7011. headers: { 'Content-Type': 'application/json' },
  7012. body: JSON.stringify(payload)
  7013. });
  7014. if (res.ok) {
  7015. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7016. closeRouteModal();
  7017. loadRoutes();
  7018. } else {
  7019. const err = await res.json();
  7020. showToast('Error', err.message || 'Failed to save route', 'error');
  7021. }
  7022. } catch (err) {
  7023. showToast('Error', err.message, 'error');
  7024. }
  7025. }
  7026. async function toggleRouteState(id, disabled) {
  7027. try {
  7028. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7029. method: 'POST',
  7030. headers: { 'Content-Type': 'application/json' },
  7031. body: JSON.stringify({ disabled })
  7032. });
  7033. if (res.ok) loadRoutes();
  7034. } catch (err) {
  7035. showToast('Error', err.message, 'error');
  7036. }
  7037. }
  7038. async function deleteRoute(id) {
  7039. if (!confirm('Are you sure you want to delete this route?')) return;
  7040. try {
  7041. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7042. if (res.ok) {
  7043. showToast('Deleted', 'Route removed', 'success');
  7044. loadRoutes();
  7045. }
  7046. } catch (err) {
  7047. showToast('Error', err.message, 'error');
  7048. }
  7049. }
  7050. // ----------------- Policy Rules (/ip route rule) -----------------
  7051. function renderPolicyRules() {
  7052. const tbody = document.getElementById('rules-table-body');
  7053. const empty = document.getElementById('rules-empty');
  7054. if (!tbody) return;
  7055. const showSystem = document.getElementById('prule-show-system')?.checked;
  7056. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7057. const countBadge = document.getElementById('rules-count-badge');
  7058. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7059. const bRules = document.getElementById('routes-badge-rules');
  7060. if (bRules) bRules.innerText = filtered.length;
  7061. if (filtered.length === 0) {
  7062. empty?.classList.remove('hidden');
  7063. tbody.innerHTML = '';
  7064. return;
  7065. }
  7066. empty?.classList.add('hidden');
  7067. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7068. if (tbody.dataset.sig === sig) return;
  7069. tbody.dataset.sig = sig;
  7070. tbody.innerHTML = '';
  7071. filtered.forEach(pr => {
  7072. const isSys = pr.is_default || pr.is_system;
  7073. const tr = document.createElement('tr');
  7074. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7075. tr.innerHTML = `
  7076. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7077. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7078. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7079. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7080. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7081. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7082. <td class="py-2.5 px-3 text-right font-sans">
  7083. ${!pr.is_default ? `
  7084. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7085. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7086. </td>
  7087. `;
  7088. tbody.appendChild(tr);
  7089. });
  7090. }
  7091. function openAddPolicyRuleModal() {
  7092. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7093. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7094. document.getElementById('prule-modal-mark').value = '';
  7095. document.getElementById('prule-modal-src').value = '';
  7096. document.getElementById('prule-modal-dst').value = '';
  7097. const sel = document.getElementById('prule-modal-table');
  7098. sel.innerHTML = '';
  7099. (state.routingTables || []).forEach(t => {
  7100. const opt = document.createElement('option');
  7101. opt.value = t.name;
  7102. opt.innerText = t.name;
  7103. sel.appendChild(opt);
  7104. });
  7105. document.getElementById('prule-modal').classList.remove('hidden');
  7106. }
  7107. function closePolicyRuleModal() {
  7108. document.getElementById('prule-modal').classList.add('hidden');
  7109. }
  7110. async function submitSavePolicyRule(e) {
  7111. e.preventDefault();
  7112. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7113. const mark = document.getElementById('prule-modal-mark').value.trim();
  7114. const src = document.getElementById('prule-modal-src').value.trim();
  7115. const dst = document.getElementById('prule-modal-dst').value.trim();
  7116. const table = document.getElementById('prule-modal-table').value;
  7117. const action = document.getElementById('prule-modal-action').value;
  7118. try {
  7119. const res = await fetch(`${API_BASE}/routing/rules`, {
  7120. method: 'POST',
  7121. headers: { 'Content-Type': 'application/json' },
  7122. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7123. });
  7124. if (res.ok) {
  7125. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7126. closePolicyRuleModal();
  7127. loadRoutes();
  7128. } else {
  7129. const err = await res.json();
  7130. showToast('Error', err.message, 'error');
  7131. }
  7132. } catch (err) {
  7133. showToast('Error', err.message, 'error');
  7134. }
  7135. }
  7136. async function deletePolicyRule(id) {
  7137. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7138. try {
  7139. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7140. if (res.ok) {
  7141. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7142. loadRoutes();
  7143. }
  7144. } catch (err) {
  7145. showToast('Error', err.message, 'error');
  7146. }
  7147. }
  7148. // ----------------- Routing Tables -----------------
  7149. function renderRoutingTables() {
  7150. const tbody = document.getElementById('tables-table-body');
  7151. if (!tbody) return;
  7152. const tables = state.routingTables || [];
  7153. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7154. if (tbody.dataset.sig === sig) return;
  7155. tbody.dataset.sig = sig;
  7156. tbody.innerHTML = '';
  7157. (state.routingTables || []).forEach(t => {
  7158. const tr = document.createElement('tr');
  7159. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7160. tr.innerHTML = `
  7161. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7162. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7163. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7164. `;
  7165. tbody.appendChild(tr);
  7166. });
  7167. }
  7168. function openAddTableModal() {
  7169. document.getElementById('table-modal-name').value = '';
  7170. document.getElementById('table-modal-id').value = '';
  7171. document.getElementById('table-modal-comment').value = '';
  7172. document.getElementById('table-modal').classList.remove('hidden');
  7173. }
  7174. function closeTableModal() {
  7175. document.getElementById('table-modal').classList.add('hidden');
  7176. }
  7177. async function submitSaveTable(e) {
  7178. e.preventDefault();
  7179. const name = document.getElementById('table-modal-name').value.trim();
  7180. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7181. const comment = document.getElementById('table-modal-comment').value.trim();
  7182. try {
  7183. const res = await fetch(`${API_BASE}/routing/tables`, {
  7184. method: 'POST',
  7185. headers: { 'Content-Type': 'application/json' },
  7186. body: JSON.stringify({ name, table_id: id, comment })
  7187. });
  7188. if (res.ok) {
  7189. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7190. closeTableModal();
  7191. loadRoutes();
  7192. } else {
  7193. const err = await res.json();
  7194. showToast('Error', err.message, 'error');
  7195. }
  7196. } catch (err) {
  7197. showToast('Error', err.message, 'error');
  7198. }
  7199. }
  7200. async function loadDebianConfig() {
  7201. const view = document.getElementById('debian-config-view');
  7202. view.innerText = 'Generating live configuration...';
  7203. try {
  7204. const res = await fetch(`${API_BASE}/debian/config`);
  7205. const data = await res.json();
  7206. view.innerText = data.content || '# Empty config';
  7207. } catch (err) {
  7208. view.innerText = 'Failed to generate Debian network config.';
  7209. }
  7210. }
  7211. async function saveDebianConfig() {
  7212. try {
  7213. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7214. const data = await res.json();
  7215. if (res.ok) {
  7216. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7217. loadDebianConfig();
  7218. }
  7219. } catch (err) {
  7220. showToast('Error', err.message, 'error');
  7221. }
  7222. }
  7223. function showToast(title, message, type = 'info') {
  7224. const container = document.getElementById('toast-container');
  7225. const toast = document.createElement('div');
  7226. const borderColors = {
  7227. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7228. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7229. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7230. };
  7231. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  7232. toast.innerHTML = `
  7233. <div class="flex-1">
  7234. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7235. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7236. </div>
  7237. `;
  7238. container.appendChild(toast);
  7239. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7240. setTimeout(() => {
  7241. toast.classList.add('opacity-0', 'translate-y-2');
  7242. setTimeout(() => toast.remove(), 300);
  7243. }, 4000);
  7244. }
  7245. function formatTraffic(bytesPerSec) {
  7246. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7247. const kb = bytesPerSec / 1024;
  7248. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7249. const mb = kb / 1024;
  7250. return `${mb.toFixed(2)} MB/s`;
  7251. }
  7252. function toggleSidebar() {
  7253. const sb = document.getElementById('sidebar');
  7254. sb.classList.toggle('-translate-x-full');
  7255. }
  7256. // ======================== EoIP (Ethernet over IP) ========================
  7257. async function loadEoIP(populate = true) {
  7258. try {
  7259. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7260. const data = await res.json();
  7261. state.eoipTunnels = Array.isArray(data) ? data : [];
  7262. const badge = document.getElementById('eoip-count-badge');
  7263. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7264. const sideBadge = document.getElementById('badge-eoip-count');
  7265. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7266. renderEoIPTunnels();
  7267. } catch (err) {
  7268. console.error('Failed to load EoIP:', err);
  7269. }
  7270. }
  7271. function renderEoIPTunnels() {
  7272. const tbody = document.getElementById('eoip-table-body');
  7273. const empty = document.getElementById('eoip-empty');
  7274. if (!tbody) return;
  7275. tbody.innerHTML = '';
  7276. const tunnels = state.eoipTunnels || [];
  7277. if (tunnels.length === 0) {
  7278. empty?.classList.remove('hidden');
  7279. return;
  7280. }
  7281. empty?.classList.add('hidden');
  7282. tunnels.forEach(t => {
  7283. const tr = document.createElement('tr');
  7284. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7285. tr.innerHTML = `
  7286. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7287. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7288. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7289. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${t.ip_address || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  7290. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7291. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7292. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7293. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7294. <td class="py-2.5 px-3 font-mono text-[11px]">
  7295. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7296. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7297. </td>
  7298. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7299. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7300. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7301. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7302. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7303. </td>
  7304. `;
  7305. tbody.appendChild(tr);
  7306. });
  7307. }
  7308. function openAddEoIPModal() {
  7309. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7310. document.getElementById('eoip-modal-id').value = '';
  7311. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7312. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7313. document.getElementById('eoip-modal-remote').value = '';
  7314. document.getElementById('eoip-modal-ip').value = '';
  7315. document.getElementById('eoip-modal-local').value = '';
  7316. document.getElementById('eoip-modal-mac').value = '';
  7317. document.getElementById('eoip-modal-mtu').value = '1500';
  7318. document.getElementById('eoip-modal-comment').value = '';
  7319. document.getElementById('eoip-modal-clampmss').checked = true;
  7320. document.getElementById('eoip-modal-disabled').checked = false;
  7321. document.getElementById('eoip-modal').classList.remove('hidden');
  7322. }
  7323. function openEditEoIPModal(id) {
  7324. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7325. if (!t) return;
  7326. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7327. document.getElementById('eoip-modal-id').value = t.id;
  7328. document.getElementById('eoip-modal-name').value = t.name;
  7329. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7330. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7331. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7332. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7333. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7334. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7335. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7336. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7337. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7338. document.getElementById('eoip-modal').classList.remove('hidden');
  7339. }
  7340. function closeEoIPModal() {
  7341. document.getElementById('eoip-modal').classList.add('hidden');
  7342. }
  7343. async function submitSaveEoIP(e) {
  7344. e.preventDefault();
  7345. const id = document.getElementById('eoip-modal-id').value;
  7346. const name = document.getElementById('eoip-modal-name').value.trim();
  7347. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7348. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7349. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7350. const local = document.getElementById('eoip-modal-local').value.trim();
  7351. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7352. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7353. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7354. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7355. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7356. try {
  7357. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7358. method: 'POST',
  7359. headers: { 'Content-Type': 'application/json' },
  7360. body: JSON.stringify({
  7361. id,
  7362. name,
  7363. tunnel_id: tunnelId,
  7364. remote_address: remote,
  7365. ip_address: ipAddress,
  7366. local_address: local,
  7367. mac_address: mac,
  7368. mtu,
  7369. clamp_mss: clampMss,
  7370. comment,
  7371. disabled
  7372. })
  7373. });
  7374. if (res.ok) {
  7375. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7376. closeEoIPModal();
  7377. loadEoIP(false);
  7378. fetchData(false);
  7379. } else {
  7380. const err = await res.json();
  7381. showToast('Error', err.message, 'error');
  7382. }
  7383. } catch (err) {
  7384. showToast('Error', err.message, 'error');
  7385. }
  7386. }
  7387. async function toggleEoIPState(id, disabled) {
  7388. try {
  7389. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7390. method: 'POST',
  7391. headers: { 'Content-Type': 'application/json' },
  7392. body: JSON.stringify({ disabled })
  7393. });
  7394. if (res.ok) {
  7395. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7396. loadEoIP(false);
  7397. fetchData(false);
  7398. }
  7399. } catch (err) {
  7400. showToast('Error', err.message, 'error');
  7401. }
  7402. }
  7403. async function deleteEoIP(id) {
  7404. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7405. try {
  7406. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7407. if (res.ok) {
  7408. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7409. loadEoIP(false);
  7410. fetchData(false);
  7411. }
  7412. } catch (err) {
  7413. showToast('Error', err.message, 'error');
  7414. }
  7415. }
  7416. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7417. async function loadVXLAN(populate = true) {
  7418. try {
  7419. const [tunnelsRes, vtepsRes] = await Promise.all([
  7420. fetch(`${API_BASE}/vpn/vxlan`),
  7421. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7422. ]);
  7423. if (tunnelsRes.ok) {
  7424. state.vxlanTunnels = await tunnelsRes.json() || [];
  7425. }
  7426. if (vtepsRes.ok) {
  7427. state.vxlanVteps = await vtepsRes.json() || [];
  7428. }
  7429. renderVXLANTable();
  7430. renderVXLANVtepsTable();
  7431. const countBadge = document.getElementById('vxlan-count-badge');
  7432. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7433. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7434. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7435. const navBadge = document.getElementById('badge-vxlan-count');
  7436. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7437. } catch (err) {
  7438. console.error('Error loading VXLAN:', err);
  7439. }
  7440. }
  7441. function renderVXLANTable() {
  7442. const tbody = document.getElementById('vxlan-table-body');
  7443. const empty = document.getElementById('vxlan-empty');
  7444. if (!tbody || !empty) return;
  7445. tbody.innerHTML = '';
  7446. const tunnels = state.vxlanTunnels || [];
  7447. if (tunnels.length === 0) {
  7448. empty.classList.remove('hidden');
  7449. return;
  7450. }
  7451. empty.classList.add('hidden');
  7452. tunnels.forEach(t => {
  7453. const tr = document.createElement('tr');
  7454. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7455. let flag = '';
  7456. if (t.disabled) {
  7457. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 font-bold border border-slate-700" title="Disabled">X</span>';
  7458. } else if (t.running) {
  7459. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 font-bold border border-amber-800/50" title="Running">R</span>';
  7460. } else {
  7461. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-rose-950 text-rose-300 font-bold border border-rose-800/50" title="Down">!</span>';
  7462. }
  7463. const vtepCount = (t.vteps || []).length;
  7464. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7465. tr.innerHTML = `
  7466. <td class="py-2.5 px-3 text-center">${flag}</td>
  7467. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7468. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7469. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7470. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.ip_address || '') || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  7471. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7472. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7473. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7474. <td class="py-2.5 px-3 font-mono">
  7475. <span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-amber-300 border border-slate-700 cursor-pointer" onclick="openAddVXLANVtepModal('${escapeHtml(t.name)}')" title="Click to add VTEP peer">${vtepCount} VTEP${vtepCount === 1 ? '' : 's'}</span>
  7476. </td>
  7477. <td class="py-2.5 px-3 font-mono text-[11px]">
  7478. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7479. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7480. </td>
  7481. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7482. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7483. <button onclick="toggleVXLANState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-amber-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7484. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7485. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7486. </td>
  7487. `;
  7488. tbody.appendChild(tr);
  7489. });
  7490. }
  7491. function renderVXLANVtepsTable() {
  7492. const tbody = document.getElementById('vxlan-vteps-table-body');
  7493. const empty = document.getElementById('vxlan-vteps-empty');
  7494. if (!tbody || !empty) return;
  7495. tbody.innerHTML = '';
  7496. const vteps = state.vxlanVteps || [];
  7497. if (vteps.length === 0) {
  7498. empty.classList.remove('hidden');
  7499. return;
  7500. }
  7501. empty.classList.add('hidden');
  7502. vteps.forEach(v => {
  7503. const tr = document.createElement('tr');
  7504. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7505. tr.innerHTML = `
  7506. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7507. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7508. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7509. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7510. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7511. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7512. </td>
  7513. `;
  7514. tbody.appendChild(tr);
  7515. });
  7516. }
  7517. function openAddVXLANModal() {
  7518. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7519. document.getElementById('vxlan-modal-id').value = '';
  7520. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7521. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7522. document.getElementById('vxlan-modal-port').value = '4789';
  7523. document.getElementById('vxlan-modal-ip').value = '';
  7524. document.getElementById('vxlan-modal-parent').value = '';
  7525. document.getElementById('vxlan-modal-local').value = '';
  7526. document.getElementById('vxlan-modal-remote').value = '';
  7527. document.getElementById('vxlan-modal-group').value = '';
  7528. document.getElementById('vxlan-modal-mac').value = '';
  7529. document.getElementById('vxlan-modal-mtu').value = '1500';
  7530. document.getElementById('vxlan-modal-comment').value = '';
  7531. document.getElementById('vxlan-modal-learning').checked = true;
  7532. document.getElementById('vxlan-modal-disabled').checked = false;
  7533. document.getElementById('vxlan-modal').classList.remove('hidden');
  7534. }
  7535. function openEditVXLANModal(id) {
  7536. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7537. if (!t) return;
  7538. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7539. document.getElementById('vxlan-modal-id').value = t.id;
  7540. document.getElementById('vxlan-modal-name').value = t.name;
  7541. document.getElementById('vxlan-modal-vni').value = t.vni;
  7542. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7543. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7544. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7545. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7546. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7547. document.getElementById('vxlan-modal-group').value = t.group || '';
  7548. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7549. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7550. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7551. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7552. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7553. document.getElementById('vxlan-modal').classList.remove('hidden');
  7554. }
  7555. function closeVXLANModal() {
  7556. document.getElementById('vxlan-modal').classList.add('hidden');
  7557. }
  7558. async function submitSaveVXLAN(e) {
  7559. e.preventDefault();
  7560. const id = document.getElementById('vxlan-modal-id').value;
  7561. const name = document.getElementById('vxlan-modal-name').value.trim();
  7562. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7563. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7564. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7565. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7566. const local = document.getElementById('vxlan-modal-local').value.trim();
  7567. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7568. const group = document.getElementById('vxlan-modal-group').value.trim();
  7569. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7570. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7571. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7572. const learning = document.getElementById('vxlan-modal-learning').checked;
  7573. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7574. try {
  7575. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7576. method: 'POST',
  7577. headers: { 'Content-Type': 'application/json' },
  7578. body: JSON.stringify({
  7579. id,
  7580. name,
  7581. vni,
  7582. port,
  7583. ip_address: ipAddress,
  7584. parent_interface: parentInterface,
  7585. local_address: local,
  7586. remote_address: remote,
  7587. group,
  7588. mac_address: mac,
  7589. mtu,
  7590. learning,
  7591. comment,
  7592. disabled
  7593. })
  7594. });
  7595. if (res.ok) {
  7596. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7597. closeVXLANModal();
  7598. loadVXLAN(false);
  7599. fetchData(false);
  7600. } else {
  7601. const err = await res.json();
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. } catch (err) {
  7605. showToast('Error', err.message, 'error');
  7606. }
  7607. }
  7608. async function toggleVXLANState(id, disabled) {
  7609. try {
  7610. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7611. method: 'POST',
  7612. headers: { 'Content-Type': 'application/json' },
  7613. body: JSON.stringify({ disabled })
  7614. });
  7615. if (res.ok) {
  7616. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7617. loadVXLAN(false);
  7618. fetchData(false);
  7619. }
  7620. } catch (err) {
  7621. showToast('Error', err.message, 'error');
  7622. }
  7623. }
  7624. async function deleteVXLAN(id) {
  7625. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7626. try {
  7627. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7628. if (res.ok) {
  7629. showToast('Deleted', 'VXLAN interface removed', 'success');
  7630. loadVXLAN(false);
  7631. fetchData(false);
  7632. }
  7633. } catch (err) {
  7634. showToast('Error', err.message, 'error');
  7635. }
  7636. }
  7637. function openAddVXLANVtepModal(defaultIface = '') {
  7638. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7639. if (sel) {
  7640. sel.innerHTML = '';
  7641. const tunnels = state.vxlanTunnels || [];
  7642. tunnels.forEach(t => {
  7643. const opt = document.createElement('option');
  7644. opt.value = t.name;
  7645. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7646. if (defaultIface && t.name === defaultIface) {
  7647. opt.selected = true;
  7648. }
  7649. sel.appendChild(opt);
  7650. });
  7651. }
  7652. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7653. document.getElementById('vxlan-vtep-modal-port').value = '';
  7654. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7655. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7656. }
  7657. function closeVXLANVtepModal() {
  7658. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7659. }
  7660. async function submitSaveVXLANVtep(e) {
  7661. e.preventDefault();
  7662. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7663. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7664. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7665. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7666. try {
  7667. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7668. method: 'POST',
  7669. headers: { 'Content-Type': 'application/json' },
  7670. body: JSON.stringify({
  7671. interface: iface,
  7672. remote_ip: remote,
  7673. port,
  7674. comment
  7675. })
  7676. });
  7677. if (res.ok) {
  7678. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7679. closeVXLANVtepModal();
  7680. loadVXLAN(false);
  7681. fetchData(false);
  7682. } else {
  7683. const err = await res.json();
  7684. showToast('Error', err.message, 'error');
  7685. }
  7686. } catch (err) {
  7687. showToast('Error', err.message, 'error');
  7688. }
  7689. }
  7690. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7691. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7692. try {
  7693. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7694. method: 'DELETE'
  7695. });
  7696. if (res.ok) {
  7697. showToast('Deleted', 'Remote VTEP removed', 'success');
  7698. loadVXLAN(false);
  7699. fetchData(false);
  7700. }
  7701. } catch (err) {
  7702. showToast('Error', err.message, 'error');
  7703. }
  7704. }
  7705. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7706. const aeroRateSamples = new Map();
  7707. const aeroLiveRates = new Map();
  7708. async function loadAeroTUN(populate = true) {
  7709. try {
  7710. const [tunnelsRes, statsRes] = await Promise.all([
  7711. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7712. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7713. ]);
  7714. if (tunnelsRes.ok) {
  7715. const data = await tunnelsRes.json();
  7716. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7717. const now = Date.now();
  7718. for (const t of state.aerotunTunnels) {
  7719. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7720. if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
  7721. aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
  7722. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7723. if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
  7724. }
  7725. }
  7726. if (statsRes.ok) {
  7727. state.aerotunStats = await statsRes.json();
  7728. }
  7729. const countBadge = document.getElementById('aerotun-count-badge');
  7730. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7731. const sideBadge = document.getElementById('badge-aerotun-count');
  7732. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7733. renderAeroTUN();
  7734. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7735. } catch (err) {
  7736. console.error('Failed to load AeroTUN:', err);
  7737. }
  7738. }
  7739. function renderAeroTUN() {
  7740. const tbody = document.getElementById('aerotun-table-body');
  7741. const empty = document.getElementById('aerotun-empty');
  7742. // Update summary cards
  7743. const stats = state.aerotunStats || {};
  7744. const tunnels = state.aerotunTunnels || [];
  7745. const statActive = document.getElementById('aerotun-stat-active');
  7746. if (statActive) {
  7747. const activeCount = tunnels.filter(t => t.connected).length;
  7748. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7749. }
  7750. const statSaved = document.getElementById('aerotun-stat-saved');
  7751. if (statSaved) {
  7752. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7753. }
  7754. const statRatio = document.getElementById('aerotun-stat-ratio');
  7755. if (statRatio) {
  7756. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7757. }
  7758. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7759. if (statTraffic) {
  7760. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7761. }
  7762. if (!tbody) return;
  7763. tbody.innerHTML = '';
  7764. if (tunnels.length === 0) {
  7765. empty?.classList.remove('hidden');
  7766. return;
  7767. }
  7768. empty?.classList.add('hidden');
  7769. tunnels.forEach(t => {
  7770. const tr = document.createElement('tr');
  7771. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7772. const modeBadge = t.mode === 'server'
  7773. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  7774. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  7775. const endpointInfo = t.mode === 'server'
  7776. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7777. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7778. const compBadge = t.compression
  7779. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  7780. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7781. const activePeer = t.connected && t.active_peer_endpoint
  7782. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last authenticated packet: ${escapeHtml(t.last_handshake || 'just now')}; dropped: ${t.dropped_packets || 0}; auth failures: ${t.auth_failures || 0}; replay drops: ${t.replay_drops || 0}${t.last_error ? '; last error: ' + escapeHtml(t.last_error) : ''}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  7783. : `<span class="text-slate-500 text-[11px]">${t.last_error ? 'Failed: ' + escapeHtml(t.last_error) : (!t.running ? (t.disabled ? 'Saved / disabled' : 'Stopped') : (t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'))}</span>`;
  7784. const rawRx = formatBytes(t.rx_bytes || 0);
  7785. const rawTx = formatBytes(t.tx_bytes || 0);
  7786. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7787. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7788. const rate = aeroLiveRates.get(t.id);
  7789. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7790. tr.innerHTML = `
  7791. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7792. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7793. <span>${escapeHtml(t.name)}</span>
  7794. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7795. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7796. </td>
  7797. <td class="py-2.5 px-3">${modeBadge}</td>
  7798. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7799. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7800. <td class="py-2.5 px-3">${compBadge}</td>
  7801. <td class="py-2.5 px-3">${activePeer}</td>
  7802. <td class="py-2.5 px-3 font-mono text-[11px]">
  7803. <span class="text-emerald-400">↓ ${rawRx}</span>
  7804. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7805. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7806. </td>
  7807. <td class="py-2.5 px-3 font-mono text-[11px]">
  7808. <span class="text-slate-400">↓ ${wireRx}</span>
  7809. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7810. </td>
  7811. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7812. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7813. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7814. ${t.running
  7815. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7816. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7817. }
  7818. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7819. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7820. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7821. </td>
  7822. `;
  7823. tbody.appendChild(tr);
  7824. });
  7825. }
  7826. async function openAeroTUNHealth(encodedID) {
  7827. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7828. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7829. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7830. document.getElementById('aerotun-compare-host').value=underlay;
  7831. document.getElementById('aerotun-compare-result').textContent='';
  7832. document.getElementById('aerotun-health-result').textContent = '';
  7833. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7834. await refreshAeroTUNHealth();
  7835. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7836. }
  7837. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7838. async function refreshAeroTUNHealth() {
  7839. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7840. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7841. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7842. try {
  7843. const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
  7844. const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
  7845. const d=t.drop_breakdown;
  7846. document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
  7847. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7848. if(!events.length){node.textContent='No events recorded yet.';return}
  7849. for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
  7850. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7851. }
  7852. async function runAeroTUNHealthCheck() {
  7853. const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
  7854. try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
  7855. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7856. finally {button.disabled=false}
  7857. }
  7858. let aeroCompareRunning=false, aeroCompareCancel=false;
  7859. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7860. async function runAeroTUNComparison() {
  7861. if(aeroCompareRunning)return;
  7862. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
  7863. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7864. if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
  7865. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7866. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7867. const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
  7868. const results=[];
  7869. try {
  7870. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7871. if(aeroCompareCancel)break;
  7872. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7873. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7874. const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
  7875. for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
  7876. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7877. const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
  7878. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7879. }
  7880. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7881. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7882. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7883. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7884. }
  7885. let aeroModalGeneration = 0;
  7886. let aeroIdentityDraft = '';
  7887. let aeroSaving = false;
  7888. let aeroPSKRequest = 0;
  7889. function discardAeroIdentityDraft(id) {
  7890. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7891. }
  7892. async function generateAeroTUNIdentity() {
  7893. const generation = aeroModalGeneration;
  7894. const retry = document.getElementById('aerotun-retry-identity');
  7895. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7896. retry.classList.add('hidden');
  7897. document.getElementById('aerotun-modal-public').value = '';
  7898. try {
  7899. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7900. if (!res.ok) throw new Error(await responseError(res));
  7901. const draft = await res.json();
  7902. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7903. aeroIdentityDraft = draft.draft_id;
  7904. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7905. updateAeroTUNSetupHint();
  7906. } catch (err) {
  7907. if (generation !== aeroModalGeneration) return;
  7908. retry.classList.remove('hidden');
  7909. updateAeroTUNSetupHint();
  7910. showToast('Identity Generation Failed', err.message, 'error');
  7911. }
  7912. }
  7913. function onAeroTUNModeChange() {
  7914. const mode = document.getElementById('aerotun-modal-mode').value;
  7915. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7916. const portInput = document.getElementById('aerotun-modal-port');
  7917. if (mode === 'server') {
  7918. if (!portInput.value) portInput.value = '51830';
  7919. endpointInput.placeholder = 'Optional / learned roaming peer';
  7920. } else {
  7921. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7922. if (!portInput.value) portInput.value = '';
  7923. }
  7924. }
  7925. function onAeroTUNPeerChange() {
  7926. const peer = document.getElementById('aerotun-modal-peer');
  7927. const allowed = document.getElementById('aerotun-modal-allowed');
  7928. const previous = peer.dataset.allowedDefault || '';
  7929. const host = peer.value.trim().split('/')[0];
  7930. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7931. if (allowed.value.trim() === previous) allowed.value = next;
  7932. peer.dataset.allowedDefault = next;
  7933. }
  7934. async function generateAeroTUNKey(automatic = false) {
  7935. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7936. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7937. try {
  7938. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7939. if (!res.ok) throw new Error(await responseError(res));
  7940. const data = await res.json();
  7941. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7942. input.value = data.key;
  7943. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7944. } catch (err) {
  7945. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7946. }
  7947. }
  7948. function updateAeroTUNSetupHint() {
  7949. const version = document.getElementById('aerotun-modal-protocol').value;
  7950. const key = document.getElementById('aerotun-modal-public').value;
  7951. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7952. const hint = document.getElementById('aerotun-setup-hint');
  7953. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7954. if (!hint) return;
  7955. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7956. }
  7957. async function copyAeroTUNPublicKey() {
  7958. const input = document.getElementById('aerotun-modal-public');
  7959. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7960. try {
  7961. await navigator.clipboard.writeText(input.value);
  7962. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7963. } catch {
  7964. input.focus(); input.select();
  7965. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7966. }
  7967. }
  7968. async function copyAeroTUNPSK() {
  7969. const input = document.getElementById('aerotun-modal-psk');
  7970. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7971. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7972. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7973. }
  7974. function openAddAeroTUNModal() {
  7975. if (aeroSaving) return;
  7976. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7977. const tunnels = state.aerotunTunnels || [];
  7978. const usedNames = new Set(tunnels.map(t => t.name));
  7979. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7980. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  7981. if (index >= 256) index = 0;
  7982. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7983. document.getElementById('aerotun-modal-id').value = '';
  7984. document.getElementById('aerotun-modal-protocol').value='3';
  7985. document.getElementById('aerotun-modal-public').value='';
  7986. document.getElementById('aerotun-modal-peerkey').value='';
  7987. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7988. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7989. document.getElementById('aerotun-modal-mode').value = 'server';
  7990. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7991. document.getElementById('aerotun-modal-endpoint').value = '';
  7992. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7993. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7994. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7995. document.getElementById('aerotun-modal-psk').value = '';
  7996. document.getElementById('aerotun-modal-mtu').value = '1420';
  7997. document.getElementById('aerotun-modal-comment').value = '';
  7998. document.getElementById('aerotun-modal-compression').checked = false;
  7999. document.getElementById('aerotun-modal-defroute').checked = false;
  8000. document.getElementById('aerotun-modal-disabled').checked = true;
  8001. document.getElementById('aerotun-modal-psk').type = 'password';
  8002. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8003. onAeroTUNModeChange();
  8004. updateAeroTUNSetupHint();
  8005. document.getElementById('aerotun-modal').classList.remove('hidden');
  8006. generateAeroTUNKey(true);
  8007. generateAeroTUNIdentity();
  8008. }
  8009. function openEditAeroTUNModal(id) {
  8010. if (aeroSaving) return;
  8011. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8012. if (!t) return;
  8013. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8014. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8015. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8016. document.getElementById('aerotun-modal-id').value = t.id;
  8017. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8018. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8019. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8020. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8021. document.getElementById('aerotun-modal-name').value = t.name;
  8022. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8023. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8024. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8025. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8026. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8027. const peerHost = (t.peer_address || '').split('/')[0];
  8028. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8029. document.getElementById('aerotun-modal-psk').value = '';
  8030. document.getElementById('aerotun-modal-psk').type = 'password';
  8031. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8032. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8033. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8034. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8035. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8036. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8037. onAeroTUNModeChange();
  8038. updateAeroTUNSetupHint();
  8039. document.getElementById('aerotun-modal').classList.remove('hidden');
  8040. }
  8041. function closeAeroTUNModal() {
  8042. if (aeroSaving) return;
  8043. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8044. document.getElementById('aerotun-modal-psk').value = '';
  8045. document.getElementById('aerotun-modal').classList.add('hidden');
  8046. }
  8047. async function submitSaveAeroTUN(e) {
  8048. e.preventDefault();
  8049. if (aeroSaving) return;
  8050. const id = document.getElementById('aerotun-modal-id').value;
  8051. const name = document.getElementById('aerotun-modal-name').value.trim();
  8052. const mode = document.getElementById('aerotun-modal-mode').value;
  8053. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8054. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8055. const local = document.getElementById('aerotun-modal-local').value.trim();
  8056. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8057. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8058. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8059. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8060. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8061. const compression = document.getElementById('aerotun-modal-compression').checked;
  8062. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8063. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8064. if (mode === 'client' && !endpoint) {
  8065. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8066. return;
  8067. }
  8068. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8069. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8070. return;
  8071. }
  8072. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8073. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8074. return;
  8075. }
  8076. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8077. if (version === 3 && !id && !aeroIdentityDraft) {
  8078. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8079. return;
  8080. }
  8081. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8082. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8083. document.getElementById('aerotun-modal-allowed').focus();
  8084. return;
  8085. }
  8086. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8087. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8088. return;
  8089. }
  8090. if (!psk && !id) {
  8091. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8092. return;
  8093. }
  8094. aeroSaving = true;
  8095. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8096. if (submit) submit.disabled = true;
  8097. try {
  8098. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8099. method: 'POST',
  8100. headers: { 'Content-Type': 'application/json' },
  8101. body: JSON.stringify({
  8102. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8103. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8104. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8105. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8106. id,
  8107. name,
  8108. mode,
  8109. listen_port: port,
  8110. remote_endpoint: endpoint,
  8111. local_address: local,
  8112. peer_address: peer,
  8113. psk,
  8114. mtu,
  8115. compression,
  8116. default_route: defaultRoute,
  8117. comment,
  8118. disabled
  8119. })
  8120. });
  8121. if (res.ok) {
  8122. await res.json();
  8123. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8124. aeroIdentityDraft = '';
  8125. aeroSaving = false;
  8126. closeAeroTUNModal();
  8127. await loadAeroTUN(false);
  8128. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8129. fetchData(false);
  8130. } else {
  8131. const err = await responseError(res);
  8132. if (err.includes('configuration saved but tunnel failed to start')) {
  8133. aeroIdentityDraft = '';
  8134. aeroSaving = false;
  8135. closeAeroTUNModal();
  8136. await loadAeroTUN(false);
  8137. showToast('Saved, but not started', err, 'error');
  8138. } else showToast('Error Saving Tunnel', err, 'error');
  8139. }
  8140. } catch (err) {
  8141. showToast('Network Error', err.message, 'error');
  8142. } finally {
  8143. aeroSaving = false;
  8144. if (submit) submit.disabled = false;
  8145. }
  8146. }
  8147. async function startAeroTUNTunnel(id) {
  8148. try {
  8149. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8150. if (res.ok) {
  8151. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8152. loadAeroTUN(false);
  8153. fetchData(false);
  8154. } else {
  8155. const err = await res.text();
  8156. showToast('Failed to Start', err, 'error');
  8157. }
  8158. } catch (err) {
  8159. showToast('Error', err.message, 'error');
  8160. }
  8161. }
  8162. async function stopAeroTUNTunnel(id) {
  8163. try {
  8164. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8165. if (res.ok) {
  8166. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8167. loadAeroTUN(false);
  8168. fetchData(false);
  8169. } else {
  8170. const err = await res.text();
  8171. showToast('Failed to Stop', err, 'error');
  8172. }
  8173. } catch (err) {
  8174. showToast('Error', err.message, 'error');
  8175. }
  8176. }
  8177. async function toggleAeroTUNState(id, disabled) {
  8178. try {
  8179. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8180. method: 'POST',
  8181. headers: { 'Content-Type': 'application/json' },
  8182. body: JSON.stringify({ disabled })
  8183. });
  8184. if (res.ok) {
  8185. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8186. loadAeroTUN(false);
  8187. fetchData(false);
  8188. }
  8189. } catch (err) {
  8190. showToast('Error', err.message, 'error');
  8191. }
  8192. }
  8193. async function deleteAeroTUN(id) {
  8194. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8195. try {
  8196. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8197. if (res.ok) {
  8198. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8199. loadAeroTUN(false);
  8200. fetchData(false);
  8201. }
  8202. } catch (err) {
  8203. showToast('Error', err.message, 'error');
  8204. }
  8205. }
  8206. // ======================== PPP Central Hub & Servers ========================
  8207. function switchPPPSubTab(tab) {
  8208. state.pppSubTab = tab;
  8209. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8210. tabs.forEach(t => {
  8211. const panel = document.getElementById(`ppp-subtab-${t}`);
  8212. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8213. if (panel) {
  8214. if (t === tab) panel.classList.remove('hidden');
  8215. else panel.classList.add('hidden');
  8216. }
  8217. if (btn) {
  8218. if (t === tab) {
  8219. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  8220. } else {
  8221. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  8222. }
  8223. }
  8224. });
  8225. const addBtn = document.getElementById('ppp-primary-add-btn');
  8226. if (addBtn) {
  8227. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8228. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8229. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8230. else addBtn.innerHTML = '<span>Save Config</span>';
  8231. }
  8232. if (tab === 'active') loadPPPSessions();
  8233. }
  8234. function openCurrentPPPModal() {
  8235. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8236. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8237. else if (state.pppSubTab === 'active') loadPPPSessions();
  8238. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8239. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8240. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8241. }
  8242. async function loadPPP(populateDropdowns = true) {
  8243. await Promise.all([
  8244. loadPPPSecrets(),
  8245. loadPPPProfiles(),
  8246. loadPPPServers(),
  8247. loadPPPSessions()
  8248. ]);
  8249. }
  8250. async function loadPPPSecrets() {
  8251. try {
  8252. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8253. const data = await res.json();
  8254. state.pppSecrets = Array.isArray(data) ? data : [];
  8255. const b = document.getElementById('ppp-badge-secrets');
  8256. if (b) b.innerText = state.pppSecrets.length;
  8257. const b2 = document.getElementById('secrets-count-badge');
  8258. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8259. renderPPPSecrets();
  8260. } catch (err) {
  8261. console.error('Failed to load PPP secrets:', err);
  8262. }
  8263. }
  8264. function renderPPPSecrets() {
  8265. const tbody = document.getElementById('secrets-table-body');
  8266. const empty = document.getElementById('secrets-empty');
  8267. if (!tbody) return;
  8268. tbody.innerHTML = '';
  8269. const secrets = state.pppSecrets || [];
  8270. if (secrets.length === 0) {
  8271. empty?.classList.remove('hidden');
  8272. return;
  8273. }
  8274. empty?.classList.add('hidden');
  8275. secrets.forEach(s => {
  8276. const tr = document.createElement('tr');
  8277. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8278. tr.innerHTML = `
  8279. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8280. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8281. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8282. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8283. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8284. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8285. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8286. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8287. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  8288. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8289. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8290. </td>
  8291. `;
  8292. tbody.appendChild(tr);
  8293. });
  8294. }
  8295. async function loadPPPProfiles() {
  8296. try {
  8297. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8298. const data = await res.json();
  8299. state.pppProfiles = Array.isArray(data) ? data : [];
  8300. const b = document.getElementById('ppp-badge-profiles');
  8301. if (b) b.innerText = state.pppProfiles.length;
  8302. const b2 = document.getElementById('profiles-count-badge');
  8303. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8304. // Populate profile selects across modals
  8305. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8306. selects.forEach(sid => {
  8307. const el = document.getElementById(sid);
  8308. if (!el) return;
  8309. const cur = el.value;
  8310. el.innerHTML = '';
  8311. state.pppProfiles.forEach(p => {
  8312. const opt = document.createElement('option');
  8313. opt.value = p.name;
  8314. opt.innerText = `${p.name} (${p.remote_address})`;
  8315. if (p.name === cur) opt.selected = true;
  8316. el.appendChild(opt);
  8317. });
  8318. });
  8319. renderPPPProfiles();
  8320. } catch (err) {
  8321. console.error('Failed to load PPP profiles:', err);
  8322. }
  8323. }
  8324. function renderPPPProfiles() {
  8325. const tbody = document.getElementById('profiles-table-body');
  8326. if (!tbody) return;
  8327. tbody.innerHTML = '';
  8328. (state.pppProfiles || []).forEach(p => {
  8329. const isDefault = p.name.startsWith('default');
  8330. const tr = document.createElement('tr');
  8331. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8332. tr.innerHTML = `
  8333. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8334. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8335. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8336. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8337. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8338. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  8339. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8340. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8341. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  8342. </td>
  8343. `;
  8344. tbody.appendChild(tr);
  8345. });
  8346. }
  8347. async function loadPPPServers() {
  8348. try {
  8349. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8350. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8351. fetch(`${API_BASE}/vpn/servers/pptp`),
  8352. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8353. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8354. ]);
  8355. if (pppoeRes.ok) {
  8356. state.pppoeServer = await pppoeRes.json();
  8357. const s = state.pppoeServer;
  8358. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8359. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8360. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8361. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8362. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8363. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8364. const pill = document.getElementById('pppoe-server-status-pill');
  8365. if (pill) {
  8366. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8367. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  8368. }
  8369. setDotBadge('ppp-badge-pppoe-state', s.running);
  8370. }
  8371. if (pptpRes.ok) {
  8372. state.pptpServer = await pptpRes.json();
  8373. const s = state.pptpServer;
  8374. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8375. document.getElementById('pptp-server-port').value = s.port || 1723;
  8376. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8377. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8378. const pill = document.getElementById('pptp-server-status-pill');
  8379. if (pill) {
  8380. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8381. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  8382. }
  8383. setDotBadge('ppp-badge-pptp-state', s.running);
  8384. }
  8385. if (l2tpRes.ok) {
  8386. state.l2tpServer = await l2tpRes.json();
  8387. const s = state.l2tpServer;
  8388. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8389. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8390. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8391. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8392. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8393. const pill = document.getElementById('l2tp-server-status-pill');
  8394. if (pill) {
  8395. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8396. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  8397. }
  8398. setDotBadge('ppp-badge-l2tp-state', s.running);
  8399. }
  8400. if (ipsecRes.ok) {
  8401. state.ipsecServer = await ipsecRes.json();
  8402. const s = state.ipsecServer;
  8403. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8404. if (modalEn) modalEn.checked = !!s.enabled;
  8405. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8406. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8407. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8408. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8409. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8410. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8411. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8412. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8413. const pill = document.getElementById('modal-ipsec-server-status');
  8414. if (pill) {
  8415. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8416. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  8417. }
  8418. }
  8419. } catch (err) {
  8420. console.error('Failed to load VPN servers:', err);
  8421. }
  8422. }
  8423. async function loadPPPSessions() {
  8424. try {
  8425. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8426. const data = await res.json();
  8427. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8428. const b = document.getElementById('ppp-badge-active');
  8429. if (b) b.innerText = state.pppActiveSessions.length;
  8430. const sideB = document.getElementById('badge-ppp-sessions');
  8431. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8432. renderPPPSessions();
  8433. } catch (err) {
  8434. console.error('Failed to load active PPP sessions:', err);
  8435. }
  8436. }
  8437. function renderPPPSessions() {
  8438. const tbody = document.getElementById('active-ppp-table-body');
  8439. const empty = document.getElementById('active-ppp-empty');
  8440. if (!tbody) return;
  8441. tbody.innerHTML = '';
  8442. const list = state.pppActiveSessions || [];
  8443. if (list.length === 0) {
  8444. empty?.classList.remove('hidden');
  8445. return;
  8446. }
  8447. empty?.classList.add('hidden');
  8448. list.forEach(s => {
  8449. const tr = document.createElement('tr');
  8450. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8451. tr.innerHTML = `
  8452. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8453. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8454. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8455. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8456. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8457. <td class="py-2.5 px-3 text-[11px]">
  8458. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8459. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8460. </td>
  8461. <td class="py-2.5 px-3 text-right font-sans">
  8462. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8463. </td>
  8464. `;
  8465. tbody.appendChild(tr);
  8466. });
  8467. }
  8468. async function disconnectPPPSession(iface) {
  8469. if (!confirm(`Disconnect session ${iface}?`)) return;
  8470. try {
  8471. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8472. if (res.ok) {
  8473. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8474. loadPPPSessions();
  8475. }
  8476. } catch (err) {
  8477. showToast('Error', err.message, 'error');
  8478. }
  8479. }
  8480. // PPP Secret Modal handlers
  8481. function openAddPPPSecretModal() {
  8482. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8483. document.getElementById('secret-modal-id').value = '';
  8484. document.getElementById('secret-modal-name').value = '';
  8485. document.getElementById('secret-modal-password').value = '';
  8486. document.getElementById('secret-modal-service').value = 'any';
  8487. document.getElementById('secret-modal-profile').value = 'default';
  8488. document.getElementById('secret-modal-local').value = '';
  8489. document.getElementById('secret-modal-remote').value = '';
  8490. document.getElementById('secret-modal-comment').value = '';
  8491. document.getElementById('secret-modal-disabled').checked = false;
  8492. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8493. }
  8494. function openEditPPPSecretModal(id) {
  8495. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8496. if (!s) return;
  8497. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8498. document.getElementById('secret-modal-id').value = s.id;
  8499. document.getElementById('secret-modal-name').value = s.name;
  8500. document.getElementById('secret-modal-password').value = s.password;
  8501. document.getElementById('secret-modal-service').value = s.service || 'any';
  8502. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8503. document.getElementById('secret-modal-local').value = s.local_address || '';
  8504. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8505. document.getElementById('secret-modal-comment').value = s.comment || '';
  8506. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8507. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8508. }
  8509. function closePPPSecretModal() {
  8510. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8511. }
  8512. async function submitSavePPPSecret(e) {
  8513. e.preventDefault();
  8514. const id = document.getElementById('secret-modal-id').value;
  8515. const name = document.getElementById('secret-modal-name').value.trim();
  8516. const password = document.getElementById('secret-modal-password').value.trim();
  8517. const service = document.getElementById('secret-modal-service').value;
  8518. const profile = document.getElementById('secret-modal-profile').value;
  8519. const local = document.getElementById('secret-modal-local').value.trim();
  8520. const remote = document.getElementById('secret-modal-remote').value.trim();
  8521. const comment = document.getElementById('secret-modal-comment').value.trim();
  8522. const disabled = document.getElementById('secret-modal-disabled').checked;
  8523. try {
  8524. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8525. method: 'POST',
  8526. headers: { 'Content-Type': 'application/json' },
  8527. body: JSON.stringify({
  8528. id,
  8529. name,
  8530. password,
  8531. service,
  8532. profile,
  8533. local_address: local,
  8534. remote_address: remote,
  8535. comment,
  8536. disabled
  8537. })
  8538. });
  8539. if (res.ok) {
  8540. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8541. closePPPSecretModal();
  8542. loadPPPSecrets();
  8543. } else {
  8544. const err = await res.json();
  8545. showToast('Error', err.message, 'error');
  8546. }
  8547. } catch (err) {
  8548. showToast('Error', err.message, 'error');
  8549. }
  8550. }
  8551. async function togglePPPSecretState(id, disabled) {
  8552. try {
  8553. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8554. method: 'POST',
  8555. headers: { 'Content-Type': 'application/json' },
  8556. body: JSON.stringify({ disabled })
  8557. });
  8558. if (res.ok) {
  8559. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8560. loadPPPSecrets();
  8561. }
  8562. } catch (err) {
  8563. showToast('Error', err.message, 'error');
  8564. }
  8565. }
  8566. async function deletePPPSecret(id) {
  8567. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8568. try {
  8569. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8570. if (res.ok) {
  8571. showToast('Deleted', 'Secret account removed', 'success');
  8572. loadPPPSecrets();
  8573. }
  8574. } catch (err) {
  8575. showToast('Error', err.message, 'error');
  8576. }
  8577. }
  8578. // PPP Profile Modal handlers
  8579. function openAddPPPProfileModal() {
  8580. document.getElementById('profile-modal-name').value = '';
  8581. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8582. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8583. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8584. document.getElementById('profile-modal-encryption').value = 'required';
  8585. document.getElementById('profile-modal-onlyone').checked = true;
  8586. document.getElementById('profile-modal-comment').value = '';
  8587. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8588. }
  8589. function closePPPProfileModal() {
  8590. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8591. }
  8592. async function submitSavePPPProfile(e) {
  8593. e.preventDefault();
  8594. const name = document.getElementById('profile-modal-name').value.trim();
  8595. const local = document.getElementById('profile-modal-local').value.trim();
  8596. const remote = document.getElementById('profile-modal-remote').value.trim();
  8597. const dns = document.getElementById('profile-modal-dns').value.trim();
  8598. const enc = document.getElementById('profile-modal-encryption').value;
  8599. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8600. const comment = document.getElementById('profile-modal-comment').value.trim();
  8601. try {
  8602. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8603. method: 'POST',
  8604. headers: { 'Content-Type': 'application/json' },
  8605. body: JSON.stringify({
  8606. id: name,
  8607. name,
  8608. local_address: local,
  8609. remote_address: remote,
  8610. dns_servers: dns,
  8611. use_encryption: enc,
  8612. only_one: onlyone,
  8613. comment
  8614. })
  8615. });
  8616. if (res.ok) {
  8617. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8618. closePPPProfileModal();
  8619. loadPPPProfiles();
  8620. } else {
  8621. const err = await res.json();
  8622. showToast('Error', err.message, 'error');
  8623. }
  8624. } catch (err) {
  8625. showToast('Error', err.message, 'error');
  8626. }
  8627. }
  8628. async function deletePPPProfile(name) {
  8629. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8630. try {
  8631. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8632. if (res.ok) {
  8633. showToast('Deleted', 'Profile removed', 'success');
  8634. loadPPPProfiles();
  8635. } else {
  8636. const err = await res.json();
  8637. showToast('Error', err.message, 'error');
  8638. }
  8639. } catch (err) {
  8640. showToast('Error', err.message, 'error');
  8641. }
  8642. }
  8643. // Server Config submissions
  8644. async function savePPPoEServerConfig(e) {
  8645. e.preventDefault();
  8646. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8647. const name = document.getElementById('pppoe-server-name').value.trim();
  8648. const iface = document.getElementById('pppoe-server-iface').value;
  8649. const profile = document.getElementById('pppoe-server-profile').value;
  8650. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8651. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8652. try {
  8653. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8654. method: 'POST',
  8655. headers: { 'Content-Type': 'application/json' },
  8656. body: JSON.stringify({
  8657. enabled,
  8658. service_name: name,
  8659. interface: iface,
  8660. default_profile: profile,
  8661. max_mtu: mtu,
  8662. max_mru: mtu,
  8663. one_session_per_host: onesession
  8664. })
  8665. });
  8666. if (res.ok) {
  8667. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8668. loadPPPServers();
  8669. fetchData(false);
  8670. } else {
  8671. const err = await res.json();
  8672. showToast('Error', err.message, 'error');
  8673. }
  8674. } catch (err) {
  8675. showToast('Error', err.message, 'error');
  8676. }
  8677. }
  8678. async function savePPTPServerConfig(e) {
  8679. e.preventDefault();
  8680. const enabled = document.getElementById('pptp-server-enabled').checked;
  8681. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8682. const profile = document.getElementById('pptp-server-profile').value;
  8683. const mppe = document.getElementById('pptp-server-mppe').checked;
  8684. try {
  8685. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8686. method: 'POST',
  8687. headers: { 'Content-Type': 'application/json' },
  8688. body: JSON.stringify({
  8689. enabled,
  8690. port,
  8691. default_profile: profile,
  8692. require_mppe: mppe
  8693. })
  8694. });
  8695. if (res.ok) {
  8696. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8697. loadPPPServers();
  8698. fetchData(false);
  8699. } else {
  8700. const err = await res.json();
  8701. showToast('Error', err.message, 'error');
  8702. }
  8703. } catch (err) {
  8704. showToast('Error', err.message, 'error');
  8705. }
  8706. }
  8707. async function saveL2TPServerConfig(e) {
  8708. e.preventDefault();
  8709. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8710. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8711. const profile = document.getElementById('l2tp-server-profile').value;
  8712. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8713. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8714. try {
  8715. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8716. method: 'POST',
  8717. headers: { 'Content-Type': 'application/json' },
  8718. body: JSON.stringify({
  8719. enabled,
  8720. port,
  8721. default_profile: profile,
  8722. use_ipsec: useipsec,
  8723. ipsec_secret: psk
  8724. })
  8725. });
  8726. if (res.ok) {
  8727. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8728. loadPPPServers();
  8729. fetchData(false);
  8730. } else {
  8731. const err = await res.json();
  8732. showToast('Error', err.message, 'error');
  8733. }
  8734. } catch (err) {
  8735. showToast('Error', err.message, 'error');
  8736. }
  8737. }
  8738. // IPSec Server Modal
  8739. function openIPSecServerModal() {
  8740. loadPPPServers();
  8741. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8742. }
  8743. function closeIPSecServerModal() {
  8744. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8745. }
  8746. async function submitSaveIPSecServer(e) {
  8747. e.preventDefault();
  8748. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8749. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8750. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8751. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8752. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8753. try {
  8754. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8755. method: 'POST',
  8756. headers: { 'Content-Type': 'application/json' },
  8757. body: JSON.stringify({
  8758. enabled,
  8759. preshared_key: psk,
  8760. pool_address: pool,
  8761. dns_servers: dns,
  8762. local_subnet: subnet
  8763. })
  8764. });
  8765. if (res.ok) {
  8766. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8767. closeIPSecServerModal();
  8768. loadPPPServers();
  8769. fetchData(false);
  8770. } else {
  8771. const err = await res.json();
  8772. showToast('Error', err.message, 'error');
  8773. }
  8774. } catch (err) {
  8775. showToast('Error', err.message, 'error');
  8776. }
  8777. }
  8778. // WireGuard Client Config Viewer
  8779. let currentWGClientConf = '';
  8780. async function openWGClientConfModal(iface, clientIP) {
  8781. try {
  8782. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8783. method: 'POST',
  8784. headers: { 'Content-Type': 'application/json' },
  8785. body: JSON.stringify({
  8786. interface: iface,
  8787. address: clientIP || '10.10.0.2/32',
  8788. dns: '1.1.1.1, 8.8.8.8'
  8789. })
  8790. });
  8791. if (res.ok) {
  8792. const data = await res.json();
  8793. currentWGClientConf = data.config;
  8794. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8795. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8796. } else {
  8797. const err = await res.json();
  8798. showToast('Error', err.message, 'error');
  8799. }
  8800. } catch (err) {
  8801. showToast('Error', err.message, 'error');
  8802. }
  8803. }
  8804. function closeWGClientConfModal() {
  8805. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8806. }
  8807. function copyWGClientConf() {
  8808. if (!currentWGClientConf) return;
  8809. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8810. }
  8811. function downloadWGClientConf() {
  8812. if (!currentWGClientConf) return;
  8813. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8814. const a = document.createElement('a');
  8815. a.href = URL.createObjectURL(blob);
  8816. a.download = 'wireguard-client.conf';
  8817. document.body.appendChild(a);
  8818. a.click();
  8819. document.body.removeChild(a);
  8820. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8821. }
  8822. // =========================================================================
  8823. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8824. // =========================================================================
  8825. state.activeDynSubTab = 'bgp-peers';
  8826. state.activeBgpSubTab = 'bgp-peers';
  8827. state.activeOspfTab = 'instances';
  8828. state.bgpInstance = null;
  8829. state.bgpPeers = [];
  8830. state.bgpNets = [];
  8831. state.bgpRoutes = [];
  8832. state.ospfInstance = null;
  8833. state.ospfInstances = [];
  8834. state.ospfAreas = [];
  8835. state.ospfAreaRanges = [];
  8836. state.ospfTemplates = [];
  8837. state.ospfLiveInterfaces = [];
  8838. state.ospfStaticNbrs = [];
  8839. state.ospfNeighbors = [];
  8840. state.ospfLSA = [];
  8841. state.ospfRoutes = [];
  8842. state.selectedOspfRow = {
  8843. instances: null,
  8844. areas: null,
  8845. 'area-ranges': null,
  8846. templates: null,
  8847. interfaces: null,
  8848. 'static-nbrs': null,
  8849. neighbors: null,
  8850. lsa: null,
  8851. };
  8852. state.ospfSort = {
  8853. instances: { col: 'name', asc: true },
  8854. areas: { col: 'name', asc: true },
  8855. ranges: { col: 'area', asc: true },
  8856. templates: { col: 'interfaces', asc: true },
  8857. live_ifaces: { col: 'interface', asc: true },
  8858. snbrs: { col: 'address', asc: true },
  8859. neighbors: { col: 'address', asc: true },
  8860. lsa: { col: 'instance', asc: true },
  8861. };
  8862. function switchBgpSubTab(subTab) {
  8863. state.activeBgpSubTab = subTab;
  8864. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8865. tabs.forEach(t => {
  8866. const el = document.getElementById(`dyn-subtab-${t}`);
  8867. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8868. if (el) el.classList.toggle('hidden', t !== subTab);
  8869. if (btn) {
  8870. if (t === subTab) {
  8871. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  8872. } else {
  8873. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  8874. }
  8875. }
  8876. });
  8877. }
  8878. function switchOspfTab(tabName) {
  8879. state.activeOspfTab = tabName;
  8880. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8881. tabs.forEach(t => {
  8882. const pane = document.getElementById(`ospf-pane-${t}`);
  8883. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8884. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8885. if (btn) {
  8886. if (t === tabName) {
  8887. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  8888. } else {
  8889. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  8890. }
  8891. }
  8892. });
  8893. }
  8894. function switchOspfSubTab(tab) {
  8895. // Legacy alias
  8896. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8897. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8898. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8899. else switchOspfTab('instances');
  8900. }
  8901. function switchDynSubTab(subTab) {
  8902. if (subTab.startsWith('bgp')) {
  8903. if (state.activeTab !== 'bgp') navigate('bgp');
  8904. switchBgpSubTab(subTab);
  8905. } else if (subTab.startsWith('ospf')) {
  8906. if (state.activeTab !== 'ospf') navigate('ospf');
  8907. switchOspfTab('instances');
  8908. }
  8909. }
  8910. async function loadDynamicRouting(showToastMsg = false) {
  8911. try {
  8912. const fetchSafeJson = async (url) => {
  8913. try {
  8914. const r = await fetch(url);
  8915. return r.ok ? await r.json() : null;
  8916. } catch (e) {
  8917. return null;
  8918. }
  8919. };
  8920. const [
  8921. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8922. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8923. selectRules, commLists, asLists,
  8924. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  8925. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  8926. babelInsts, babelIfaces, 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/neighbors`),
  8956. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  8957. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  8958. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`)
  8959. ]);
  8960. if (sum) state.dynSummary = sum;
  8961. if (bgpInst) state.bgpInstance = bgpInst;
  8962. if (bgpPeers) state.bgpPeers = bgpPeers;
  8963. if (bgpNets) state.bgpNets = bgpNets;
  8964. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8965. if (ospfInsts) state.ospfInstances = ospfInsts;
  8966. if (ospfAreas) state.ospfAreas = ospfAreas;
  8967. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8968. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8969. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8970. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8971. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8972. if (ospfLsa) state.ospfLSA = ospfLsa;
  8973. if (filters) state.routingFilters = filters;
  8974. if (commLists) state.routingCommunityLists = commLists;
  8975. if (asLists) state.routingASLists = asLists;
  8976. if (ripInsts) state.ripInstances = ripInsts;
  8977. if (ripIfaces) state.ripInterfaces = ripIfaces;
  8978. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  8979. if (ripRoutes) state.ripRoutes = ripRoutes;
  8980. if (bfdInst) state.bfdInstance = bfdInst;
  8981. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  8982. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  8983. if (bfdSessions) state.bfdSessions = bfdSessions;
  8984. if (babelInsts) state.babelInstances = babelInsts;
  8985. if (babelIfaces) state.babelInterfaces = babelIfaces;
  8986. if (babelNbrs) state.babelNeighbors = babelNbrs;
  8987. if (babelRoutes) state.babelRoutes = babelRoutes;
  8988. if (radvInsts) state.radvInstances = radvInsts;
  8989. if (radvIfaces) state.radvInterfaces = radvIfaces;
  8990. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8991. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8992. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8993. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8994. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8995. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8996. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8997. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  8998. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  8999. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9000. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9001. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9002. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9003. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9004. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9005. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9006. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9007. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9008. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9009. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9010. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9011. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9012. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9013. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9014. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9015. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9016. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9017. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9018. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9019. } catch (err) {
  9020. console.error('Failed to load dynamic routing:', err);
  9021. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9022. }
  9023. }
  9024. async function loadOspfAll() {
  9025. await loadDynamicRouting(true);
  9026. }
  9027. function renderBgpStatusPill() {
  9028. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9029. pills.forEach(pill => {
  9030. const inst = state.bgpInstance;
  9031. if (!inst || !inst.enabled) {
  9032. 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';
  9033. pill.innerText = 'BGP DISABLED';
  9034. } else if (inst.running) {
  9035. 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';
  9036. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9037. } else {
  9038. 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';
  9039. pill.innerText = 'BGP STARTING...';
  9040. }
  9041. });
  9042. }
  9043. function renderBgpPeers() {
  9044. const tbody = document.getElementById('bgp-peers-table-body');
  9045. if (!tbody) return;
  9046. const empty = document.getElementById('bgp-peers-empty');
  9047. const countBadge = document.getElementById('bgp-peers-count-badge');
  9048. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9049. const peers = state.bgpPeers || [];
  9050. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9051. if (navBadge) navBadge.innerText = peers.length;
  9052. if (peers.length === 0) {
  9053. tbody.innerHTML = '';
  9054. if (empty) empty.classList.remove('hidden');
  9055. return;
  9056. }
  9057. if (empty) empty.classList.add('hidden');
  9058. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9059. if (tbody.dataset.sig === sig) return;
  9060. tbody.dataset.sig = sig;
  9061. tbody.innerHTML = peers.map(p => {
  9062. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9063. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9064. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9065. let stateBadge = '';
  9066. if (p.disabled) {
  9067. 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>';
  9068. } else if (p.state === 'Established') {
  9069. 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>';
  9070. } else if (p.state === 'Connect' || p.state === 'Active') {
  9071. 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>`;
  9072. } else {
  9073. 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>`;
  9074. }
  9075. return `
  9076. <tr class="hover:bg-slate-800/40 transition">
  9077. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9078. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9079. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9080. <td class="py-2.5 px-3">
  9081. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9082. ${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>`}
  9083. </td>
  9084. <td class="py-2.5 px-3">${stateBadge}</td>
  9085. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9086. <td class="py-2.5 px-3 text-slate-300">
  9087. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9088. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9089. </td>
  9090. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9091. ${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> ` : ''}
  9092. ${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>` : ''}
  9093. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9094. </td>
  9095. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9096. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9097. <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'}">
  9098. ${p.disabled ? 'Enable' : 'Disable'}
  9099. </button>
  9100. <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">
  9101. Edit
  9102. </button>
  9103. <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">
  9104. Delete
  9105. </button>
  9106. </td>
  9107. </tr>
  9108. `;
  9109. }).join('');
  9110. }
  9111. function renderBgpNetworks() {
  9112. const tbody = document.getElementById('bgp-nets-table-body');
  9113. if (!tbody) return;
  9114. const empty = document.getElementById('bgp-nets-empty');
  9115. const countBadge = document.getElementById('bgp-nets-count-badge');
  9116. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9117. const nets = state.bgpNets || [];
  9118. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9119. if (navBadge) navBadge.innerText = nets.length;
  9120. if (nets.length === 0) {
  9121. tbody.innerHTML = '';
  9122. if (empty) empty.classList.remove('hidden');
  9123. return;
  9124. }
  9125. if (empty) empty.classList.add('hidden');
  9126. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9127. if (tbody.dataset.sig === sig) return;
  9128. tbody.dataset.sig = sig;
  9129. tbody.innerHTML = nets.map(n => `
  9130. <tr class="hover:bg-slate-800/40 transition">
  9131. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9132. <td class="py-2.5 px-3">
  9133. ${n.disabled
  9134. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9135. : '<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>'}
  9136. </td>
  9137. <td class="py-2.5 px-3">
  9138. ${n.disabled
  9139. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9140. : '<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>'}
  9141. </td>
  9142. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9143. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9144. <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">
  9145. Delete
  9146. </button>
  9147. </td>
  9148. </tr>
  9149. `).join('');
  9150. }
  9151. function renderBgpRoutes() {
  9152. const tbody = document.getElementById('bgp-routes-table-body');
  9153. if (!tbody) return;
  9154. const empty = document.getElementById('bgp-routes-empty');
  9155. const countBadge = document.getElementById('bgp-routes-count-badge');
  9156. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9157. const routes = state.bgpRoutes || [];
  9158. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9159. if (navBadge) navBadge.innerText = routes.length;
  9160. if (routes.length === 0) {
  9161. tbody.innerHTML = '';
  9162. if (empty) empty.classList.remove('hidden');
  9163. return;
  9164. }
  9165. if (empty) empty.classList.add('hidden');
  9166. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9167. if (tbody.dataset.sig === sig) return;
  9168. tbody.dataset.sig = sig;
  9169. tbody.innerHTML = routes.map(r => `
  9170. <tr class="hover:bg-slate-800/40 transition">
  9171. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9172. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9173. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9174. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9175. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9176. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9177. </tr>
  9178. `).join('');
  9179. }
  9180. // =========================================================================
  9181. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9182. // =========================================================================
  9183. function sortOspfTable(tab, col) {
  9184. if (!state.ospfSort) state.ospfSort = {};
  9185. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9186. if (state.ospfSort[tab].col === col) {
  9187. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9188. } else {
  9189. state.ospfSort[tab].col = col;
  9190. state.ospfSort[tab].asc = true;
  9191. }
  9192. const asc = state.ospfSort[tab].asc;
  9193. let list = [];
  9194. if (tab === 'instances') list = state.ospfInstances || [];
  9195. else if (tab === 'areas') list = state.ospfAreas || [];
  9196. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9197. else if (tab === 'templates') list = state.ospfTemplates || [];
  9198. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9199. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9200. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9201. else if (tab === 'lsa') list = state.ospfLSA || [];
  9202. list.sort((a, b) => {
  9203. let valA = a[col] ?? '';
  9204. let valB = b[col] ?? '';
  9205. if (typeof valA === 'number' && typeof valB === 'number') {
  9206. return asc ? valA - valB : valB - valA;
  9207. }
  9208. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9209. });
  9210. if (tab === 'instances') renderOspfInstances();
  9211. else if (tab === 'areas') renderOspfAreas();
  9212. else if (tab === 'ranges') renderOspfAreaRanges();
  9213. else if (tab === 'templates') renderOspfTemplates();
  9214. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9215. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9216. else if (tab === 'neighbors') renderOspfNeighbors();
  9217. else if (tab === 'lsa') renderOspfLSA();
  9218. }
  9219. function selectOspfRow(tab, id) {
  9220. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9221. state.selectedOspfRow[tab] = id;
  9222. if (tab === 'instances') {
  9223. renderOspfInstances();
  9224. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9225. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9226. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9227. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9228. if (btnEn) btnEn.disabled = false;
  9229. if (btnDis) btnDis.disabled = false;
  9230. if (btnRem) btnRem.disabled = false;
  9231. if (btnCom) btnCom.disabled = false;
  9232. } else if (tab === 'areas') {
  9233. renderOspfAreas();
  9234. const btnEn = document.getElementById('btn-ospf-area-enable');
  9235. const btnDis = document.getElementById('btn-ospf-area-disable');
  9236. const btnRem = document.getElementById('btn-ospf-area-remove');
  9237. const btnCom = document.getElementById('btn-ospf-area-comment');
  9238. if (btnEn) btnEn.disabled = false;
  9239. if (btnDis) btnDis.disabled = false;
  9240. if (btnRem) btnRem.disabled = false;
  9241. if (btnCom) btnCom.disabled = false;
  9242. } else if (tab === 'ranges') {
  9243. renderOspfAreaRanges();
  9244. const btnEn = document.getElementById('btn-ospf-range-enable');
  9245. const btnDis = document.getElementById('btn-ospf-range-disable');
  9246. const btnRem = document.getElementById('btn-ospf-range-remove');
  9247. const btnCom = document.getElementById('btn-ospf-range-comment');
  9248. if (btnEn) btnEn.disabled = false;
  9249. if (btnDis) btnDis.disabled = false;
  9250. if (btnRem) btnRem.disabled = false;
  9251. if (btnCom) btnCom.disabled = false;
  9252. } else if (tab === 'templates') {
  9253. renderOspfTemplates();
  9254. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9255. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9256. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9257. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9258. if (btnEn) btnEn.disabled = false;
  9259. if (btnDis) btnDis.disabled = false;
  9260. if (btnRem) btnRem.disabled = false;
  9261. if (btnCom) btnCom.disabled = false;
  9262. } else if (tab === 'snbrs') {
  9263. renderOspfStaticNbrs();
  9264. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9265. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9266. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9267. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9268. if (btnEn) btnEn.disabled = false;
  9269. if (btnDis) btnDis.disabled = false;
  9270. if (btnRem) btnRem.disabled = false;
  9271. if (btnCom) btnCom.disabled = false;
  9272. }
  9273. }
  9274. // TAB 1: INSTANCES
  9275. function renderOspfInstances() {
  9276. const tbody = document.getElementById('ospf-instances-table-body');
  9277. if (!tbody) return;
  9278. const countEl = document.getElementById('ospf-instances-footer-count');
  9279. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9280. let list = state.ospfInstances || [];
  9281. if (filter) {
  9282. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9283. }
  9284. if (countEl) countEl.innerText = list.length;
  9285. const selId = state.selectedOspfRow?.instances;
  9286. tbody.innerHTML = list.map((inst, idx) => {
  9287. const isSel = inst.id === selId;
  9288. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9289. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9290. const redist = [];
  9291. if (inst.redistribute_connected) redist.push('conn');
  9292. if (inst.redistribute_static) redist.push('static');
  9293. if (inst.redistribute_bgp) redist.push('bgp');
  9294. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9295. redist.push('default');
  9296. }
  9297. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9298. const origBadge = origDef === 'always'
  9299. ? '<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>'
  9300. : (origDef === 'if-installed'
  9301. ? '<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>'
  9302. : '<span class="text-slate-500 text-[10px]">never</span>');
  9303. return `
  9304. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9305. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9306. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9307. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9308. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9309. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9310. </td>
  9311. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9312. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9313. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9314. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9315. <td class="py-1.5 px-3">${origBadge}</td>
  9316. </tr>
  9317. `;
  9318. }).join('');
  9319. }
  9320. // TAB 2: AREAS
  9321. function renderOspfAreas() {
  9322. const tbody = document.getElementById('ospf-areas-table-body');
  9323. if (!tbody) return;
  9324. const countEl = document.getElementById('ospf-areas-footer-count');
  9325. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9326. let list = state.ospfAreas || [];
  9327. if (filter) {
  9328. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9329. }
  9330. if (countEl) countEl.innerText = list.length;
  9331. const selId = state.selectedOspfRow?.areas;
  9332. tbody.innerHTML = list.map((a, idx) => {
  9333. const isSel = a.id === selId;
  9334. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9335. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9336. return `
  9337. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9338. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9339. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9340. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9341. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9342. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9343. </td>
  9344. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9345. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9346. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9347. </tr>
  9348. `;
  9349. }).join('');
  9350. }
  9351. // TAB 3: AREA RANGES
  9352. function renderOspfAreaRanges() {
  9353. const tbody = document.getElementById('ospf-ranges-table-body');
  9354. if (!tbody) return;
  9355. const countEl = document.getElementById('ospf-ranges-footer-count');
  9356. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9357. let list = state.ospfAreaRanges || [];
  9358. if (filter) {
  9359. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9360. }
  9361. if (countEl) countEl.innerText = list.length;
  9362. const selId = state.selectedOspfRow?.['area-ranges'];
  9363. tbody.innerHTML = list.map((r, idx) => {
  9364. const isSel = r.id === selId;
  9365. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9366. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9367. return `
  9368. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9369. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9370. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9371. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9372. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9373. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9374. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9375. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9376. </tr>
  9377. `;
  9378. }).join('');
  9379. }
  9380. // TAB 4: INTERFACE TEMPLATES
  9381. function renderOspfTemplates() {
  9382. const tbody = document.getElementById('ospf-templates-table-body');
  9383. if (!tbody) return;
  9384. const countEl = document.getElementById('ospf-templates-footer-count');
  9385. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9386. let list = state.ospfTemplates || [];
  9387. if (filter) {
  9388. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9389. }
  9390. if (countEl) countEl.innerText = list.length;
  9391. const selId = state.selectedOspfRow?.templates;
  9392. tbody.innerHTML = list.map((t, idx) => {
  9393. const isSel = t.id === selId;
  9394. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9395. const ifaces = t.interfaces || t.interface || 'all';
  9396. const nets = t.networks || t.network || '';
  9397. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9398. return `
  9399. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9400. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9401. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9402. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9403. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9404. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9405. </td>
  9406. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9407. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9408. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9409. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9410. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9411. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9412. </tr>
  9413. `;
  9414. }).join('');
  9415. }
  9416. // TAB 5: LIVE INTERFACES
  9417. function renderOspfLiveInterfaces() {
  9418. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9419. if (!tbody) return;
  9420. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9421. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9422. let list = state.ospfLiveInterfaces || [];
  9423. if (filter) {
  9424. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9425. }
  9426. if (countEl) countEl.innerText = list.length;
  9427. tbody.innerHTML = list.map(i => `
  9428. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9429. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9430. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9431. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9432. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9433. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9434. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9435. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9436. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9437. </tr>
  9438. `).join('');
  9439. }
  9440. // TAB 6: STATIC NEIGHBORS
  9441. function renderOspfStaticNbrs() {
  9442. const tbody = document.getElementById('ospf-snbrs-table-body');
  9443. if (!tbody) return;
  9444. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9445. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9446. let list = state.ospfStaticNbrs || [];
  9447. if (filter) {
  9448. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9449. }
  9450. if (countEl) countEl.innerText = list.length;
  9451. const selId = state.selectedOspfRow?.['static-nbrs'];
  9452. tbody.innerHTML = list.map((n, idx) => {
  9453. const isSel = n.id === selId;
  9454. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9455. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9456. return `
  9457. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9458. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9459. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9460. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9461. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9462. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9463. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9464. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9465. </tr>
  9466. `;
  9467. }).join('');
  9468. }
  9469. // TAB 7: LIVE NEIGHBORS
  9470. function renderOspfNeighbors() {
  9471. const tbody = document.getElementById('ospf-neighbors-table-body');
  9472. if (!tbody) return;
  9473. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9474. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9475. let list = state.ospfNeighbors || [];
  9476. if (filter) {
  9477. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9478. }
  9479. if (countEl) countEl.innerText = list.length;
  9480. tbody.innerHTML = list.map(n => `
  9481. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9482. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9483. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9484. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9485. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9486. </td>
  9487. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9488. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9489. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9490. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9491. </tr>
  9492. `).join('');
  9493. }
  9494. // TAB 8: LINK-STATE DATABASE (LSA)
  9495. function renderOspfLSA() {
  9496. const tbody = document.getElementById('ospf-lsa-table-body');
  9497. if (!tbody) return;
  9498. const countEl = document.getElementById('ospf-lsa-footer-count');
  9499. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9500. let list = state.ospfLSA || [];
  9501. if (filter) {
  9502. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9503. }
  9504. if (countEl) countEl.innerText = list.length;
  9505. tbody.innerHTML = list.map(l => `
  9506. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9507. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9508. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9509. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9510. </td>
  9511. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9512. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9513. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9514. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9515. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9516. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9517. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9518. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9519. </tr>
  9520. `).join('');
  9521. }
  9522. function renderOspfStatusPill() {
  9523. // Maintained for backward compatibility
  9524. const pill = document.getElementById('ospf-live-status-pill');
  9525. if (!pill) return;
  9526. 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';
  9527. pill.innerText = 'OSPF ACTIVE';
  9528. }
  9529. function renderOspfInterfaces() {
  9530. renderOspfTemplates();
  9531. }
  9532. function renderOspfRoutes() {
  9533. // Routes retained in background
  9534. }
  9535. // BGP Modals & Actions
  9536. function openBgpInstanceModal() {
  9537. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9538. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9539. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9540. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9541. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9542. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9543. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9544. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9545. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9546. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9547. }
  9548. function closeBgpInstanceModal() {
  9549. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9550. }
  9551. async function submitBgpInstance(e) {
  9552. e.preventDefault();
  9553. const payload = {
  9554. enabled: document.getElementById('modal-bgp-enabled').checked,
  9555. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9556. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9557. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9558. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9559. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9560. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9561. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9562. };
  9563. try {
  9564. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9565. method: 'POST',
  9566. headers: { 'Content-Type': 'application/json' },
  9567. body: JSON.stringify(payload)
  9568. });
  9569. if (res.ok) {
  9570. closeBgpInstanceModal();
  9571. showToast('Success', 'BGP instance configuration updated', 'success');
  9572. loadDynamicRouting();
  9573. } else {
  9574. const err = await res.json();
  9575. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9576. }
  9577. } catch (err) {
  9578. showToast('Error', err.message, 'error');
  9579. }
  9580. }
  9581. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9582. function switchBgpPeerModalTab(tab) {
  9583. // Normalize legacy tab names
  9584. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9585. if (tab === 'attributes') tab = 'networks';
  9586. const tabs = ['general', 'filters', 'networks'];
  9587. tabs.forEach(t => {
  9588. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9589. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9590. if (t === tab) {
  9591. if (pane) pane.classList.remove('hidden');
  9592. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9593. } else {
  9594. if (pane) pane.classList.add('hidden');
  9595. 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';
  9596. }
  9597. });
  9598. }
  9599. function addOutputNetworkRow(val = '') {
  9600. const container = document.getElementById('modal-bgp-output-networks-container');
  9601. if (!container) return;
  9602. const row = document.createElement('div');
  9603. row.className = 'flex items-center gap-2 output-net-row';
  9604. row.innerHTML = `
  9605. <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">
  9606. <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>
  9607. `;
  9608. container.appendChild(row);
  9609. }
  9610. function parseBgpTime(val) {
  9611. if (!val) return 0;
  9612. val = String(val).trim();
  9613. if (val.includes(':')) {
  9614. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9615. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9616. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9617. }
  9618. return parseInt(val, 10) || 0;
  9619. }
  9620. function formatBgpTime(secs) {
  9621. if (!secs || secs <= 0) return '30';
  9622. return String(secs);
  9623. }
  9624. function populateBgpRoutingTables() {
  9625. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9626. if (!sel) return;
  9627. const cur = sel.value || 'main';
  9628. sel.innerHTML = '<option value="main">main</option>';
  9629. (state.routingTables || []).forEach(t => {
  9630. if (t.name !== 'main') {
  9631. const opt = document.createElement('option');
  9632. opt.value = t.name;
  9633. opt.innerText = t.name;
  9634. sel.appendChild(opt);
  9635. }
  9636. });
  9637. sel.value = cur;
  9638. }
  9639. function openAddBgpPeerModal() {
  9640. document.getElementById('bgp-peer-form').reset();
  9641. document.getElementById('modal-bgp-peer-id').value = '';
  9642. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9643. // General Tab
  9644. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9645. document.getElementById('modal-bgp-peer-name').value = '';
  9646. document.getElementById('modal-bgp-peer-comment').value = '';
  9647. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9648. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9649. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9650. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9651. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9652. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9653. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9654. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9655. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9656. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9657. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9658. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9659. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9660. // Filters Tab
  9661. populateFilterChainsDatalist();
  9662. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9663. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9664. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9665. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9666. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9667. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9668. // Advertised Networks Tab
  9669. const container = document.getElementById('modal-bgp-output-networks-container');
  9670. if (container) {
  9671. container.innerHTML = '';
  9672. addOutputNetworkRow('');
  9673. }
  9674. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9675. if (removeBtn) removeBtn.classList.add('hidden');
  9676. switchBgpPeerModalTab('general');
  9677. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9678. }
  9679. function populateFilterChainsDatalist() {
  9680. const dl = document.getElementById('filter-chains-list');
  9681. if (!dl) return;
  9682. const chains = new Set();
  9683. (state.routingFilters || []).forEach(f => {
  9684. if (f.chain) chains.add(f.chain);
  9685. });
  9686. if (chains.size === 0) {
  9687. chains.add('awmn');
  9688. chains.add('Internal');
  9689. chains.add('bgp-in');
  9690. chains.add('bgp-out');
  9691. }
  9692. dl.innerHTML = '';
  9693. chains.forEach(c => {
  9694. const opt = document.createElement('option');
  9695. opt.value = c;
  9696. dl.appendChild(opt);
  9697. });
  9698. }
  9699. function openEditBgpPeerModal(id) {
  9700. const p = (state.bgpPeers || []).find(item => item.id === id);
  9701. if (!p) return;
  9702. populateFilterChainsDatalist();
  9703. document.getElementById('modal-bgp-peer-id').value = p.id;
  9704. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9705. // General Tab
  9706. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9707. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9708. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9709. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9710. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9711. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9712. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9713. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9714. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9715. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9716. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9717. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9718. // Passive mode
  9719. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9720. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9721. // Next-hop self
  9722. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9723. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9724. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9725. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9726. // Filters Tab
  9727. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9728. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9729. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9730. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9731. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9732. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9733. // Advertised Networks Tab
  9734. const container = document.getElementById('modal-bgp-output-networks-container');
  9735. if (container) {
  9736. container.innerHTML = '';
  9737. if (p.output_networks && p.output_networks.length > 0) {
  9738. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9739. } else {
  9740. addOutputNetworkRow('');
  9741. }
  9742. }
  9743. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9744. if (removeBtn) removeBtn.classList.remove('hidden');
  9745. switchBgpPeerModalTab('general');
  9746. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9747. }
  9748. function copyCurrentBgpPeer() {
  9749. document.getElementById('modal-bgp-peer-id').value = '';
  9750. const nameEl = document.getElementById('modal-bgp-peer-name');
  9751. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9752. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9753. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9754. if (removeBtn) removeBtn.classList.add('hidden');
  9755. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9756. }
  9757. function removeCurrentBgpPeer() {
  9758. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9759. if (!id) return;
  9760. deleteBgpPeer(id);
  9761. closeBgpPeerModal();
  9762. }
  9763. function closeBgpPeerModal() {
  9764. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9765. }
  9766. function getBgpPeerFormData() {
  9767. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9768. const outputNetworks = [];
  9769. netInputs.forEach(inp => {
  9770. const v = inp.value.trim();
  9771. if (v) outputNetworks.push(v);
  9772. });
  9773. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9774. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9775. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9776. return {
  9777. id: document.getElementById('modal-bgp-peer-id').value,
  9778. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9779. enabled: enabled,
  9780. disabled: !enabled,
  9781. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9782. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9783. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9784. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9785. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9786. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9787. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9788. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9789. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9790. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9791. passive: isPassive,
  9792. connect: !isPassive,
  9793. listen: true,
  9794. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9795. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9796. nexthop_self: isNexthopSelf,
  9797. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9798. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9799. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9800. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9801. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9802. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9803. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9804. output_networks: outputNetworks
  9805. };
  9806. }
  9807. async function submitBgpPeer(e) {
  9808. if (e) e.preventDefault();
  9809. const payload = getBgpPeerFormData();
  9810. try {
  9811. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9812. method: 'POST',
  9813. headers: { 'Content-Type': 'application/json' },
  9814. body: JSON.stringify(payload)
  9815. });
  9816. if (res.ok) {
  9817. closeBgpPeerModal();
  9818. showToast('Success', 'BGP Connection saved', 'success');
  9819. loadDynamicRouting();
  9820. } else {
  9821. const err = await res.json();
  9822. showToast('Error', err.error || 'Failed to save peer', 'error');
  9823. }
  9824. } catch (err) {
  9825. showToast('Error', err.message, 'error');
  9826. }
  9827. }
  9828. async function applyBgpPeerModal(e) {
  9829. if (e) e.preventDefault();
  9830. const payload = getBgpPeerFormData();
  9831. try {
  9832. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9833. method: 'POST',
  9834. headers: { 'Content-Type': 'application/json' },
  9835. body: JSON.stringify(payload)
  9836. });
  9837. if (res.ok) {
  9838. const data = await res.json();
  9839. if (data.peer && data.peer.id) {
  9840. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9841. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9842. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9843. }
  9844. showToast('Applied', 'BGP Connection applied', 'success');
  9845. loadDynamicRouting();
  9846. } else {
  9847. const err = await res.json();
  9848. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9849. }
  9850. } catch (err) {
  9851. showToast('Error', err.message, 'error');
  9852. }
  9853. }
  9854. async function deleteBgpPeer(id) {
  9855. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9856. try {
  9857. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9858. if (res.ok) {
  9859. showToast('Deleted', 'BGP peer removed', 'success');
  9860. loadDynamicRouting();
  9861. }
  9862. } catch (err) {
  9863. showToast('Error', err.message, 'error');
  9864. }
  9865. }
  9866. async function toggleBgpPeerState(id, disabled) {
  9867. try {
  9868. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9869. method: 'POST',
  9870. headers: { 'Content-Type': 'application/json' },
  9871. body: JSON.stringify({ disabled })
  9872. });
  9873. if (res.ok) {
  9874. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9875. loadDynamicRouting();
  9876. }
  9877. } catch (err) {
  9878. showToast('Error', err.message, 'error');
  9879. }
  9880. }
  9881. function openAddBgpNetworkModal() {
  9882. document.getElementById('bgp-network-form').reset();
  9883. document.getElementById('modal-bgp-net-id').value = '';
  9884. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9885. }
  9886. function closeBgpNetworkModal() {
  9887. document.getElementById('bgp-network-modal').classList.add('hidden');
  9888. }
  9889. async function submitBgpNetwork(e) {
  9890. e.preventDefault();
  9891. const payload = {
  9892. id: document.getElementById('modal-bgp-net-id').value,
  9893. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9894. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9895. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9896. };
  9897. try {
  9898. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9899. method: 'POST',
  9900. headers: { 'Content-Type': 'application/json' },
  9901. body: JSON.stringify(payload)
  9902. });
  9903. if (res.ok) {
  9904. closeBgpNetworkModal();
  9905. showToast('Success', 'BGP network advertisement saved', 'success');
  9906. loadDynamicRouting();
  9907. } else {
  9908. const err = await res.json();
  9909. showToast('Error', err.error || 'Failed to save network', 'error');
  9910. }
  9911. } catch (err) {
  9912. showToast('Error', err.message, 'error');
  9913. }
  9914. }
  9915. async function deleteBgpNetwork(id) {
  9916. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9917. try {
  9918. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9919. if (res.ok) {
  9920. showToast('Deleted', 'Network advertisement removed', 'success');
  9921. loadDynamicRouting();
  9922. }
  9923. } catch (err) {
  9924. showToast('Error', err.message, 'error');
  9925. }
  9926. }
  9927. // =========================================================================
  9928. // DEBTIK v7 OSPF MODALS & ACTIONS
  9929. // =========================================================================
  9930. // --- 1. OSPF INSTANCE ---
  9931. function openOspfInstanceModal(id = null) {
  9932. const isEdit = !!id;
  9933. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9934. id: '',
  9935. name: 'Default',
  9936. version: 2,
  9937. vrf: 'main',
  9938. router_id: '192.168.131.56',
  9939. routing_table: 'main',
  9940. enabled: true,
  9941. redistribute_connected: false,
  9942. redistribute_static: true,
  9943. redistribute_bgp: false,
  9944. comment: ''
  9945. };
  9946. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9947. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9948. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9949. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9950. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9951. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9952. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9953. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9954. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9955. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9956. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9957. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9958. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  9959. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9960. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  9961. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  9962. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  9963. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9964. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9965. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9966. }
  9967. function toggleOspfDefaultModeUI() {
  9968. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  9969. const select = document.getElementById('modal-ospf-inst-originate-default');
  9970. if (!select) return;
  9971. if (isChecked) {
  9972. if (select.value === 'never') select.value = 'if-installed';
  9973. } else {
  9974. select.value = 'never';
  9975. }
  9976. }
  9977. function onOspfOriginateDefaultChange() {
  9978. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  9979. const chk = document.getElementById('modal-ospf-inst-redist-default');
  9980. if (chk) chk.checked = val !== 'never';
  9981. }
  9982. function openEditOspfInstanceModal(id) {
  9983. openOspfInstanceModal(id);
  9984. }
  9985. function closeOspfInstanceModal() {
  9986. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9987. }
  9988. async function submitOspfInstance(e) {
  9989. if (e) e.preventDefault();
  9990. const payload = {
  9991. id: document.getElementById('modal-ospf-inst-id').value,
  9992. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9993. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9994. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9995. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9996. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9997. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9998. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9999. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10000. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10001. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10002. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10003. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10004. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10005. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  10006. };
  10007. try {
  10008. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10009. method: 'POST',
  10010. headers: { 'Content-Type': 'application/json' },
  10011. body: JSON.stringify(payload)
  10012. });
  10013. if (res.ok) {
  10014. closeOspfInstanceModal();
  10015. showToast('Saved', 'OSPF instance updated', 'success');
  10016. loadDynamicRouting();
  10017. } else {
  10018. const err = await res.json();
  10019. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10020. }
  10021. } catch (err) {
  10022. showToast('Error', err.message, 'error');
  10023. }
  10024. }
  10025. function applyOspfInstanceForm() {
  10026. submitOspfInstance(null);
  10027. }
  10028. function copyOspfInstance() {
  10029. document.getElementById('modal-ospf-inst-id').value = '';
  10030. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10031. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10032. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10033. }
  10034. async function deleteCurrentOspfInstance() {
  10035. const id = document.getElementById('modal-ospf-inst-id').value;
  10036. if (!id) return;
  10037. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10038. try {
  10039. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10040. if (res.ok) {
  10041. closeOspfInstanceModal();
  10042. showToast('Removed', 'OSPF instance deleted', 'success');
  10043. loadDynamicRouting();
  10044. }
  10045. } catch (err) {
  10046. showToast('Error', err.message, 'error');
  10047. }
  10048. }
  10049. async function enableSelectedOspfInstance() {
  10050. const id = state.selectedOspfRow?.instances;
  10051. if (!id) return;
  10052. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10053. method: 'POST',
  10054. headers: { 'Content-Type': 'application/json' },
  10055. body: JSON.stringify({ disabled: false })
  10056. });
  10057. loadDynamicRouting();
  10058. }
  10059. async function disableSelectedOspfInstance() {
  10060. const id = state.selectedOspfRow?.instances;
  10061. if (!id) return;
  10062. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10063. method: 'POST',
  10064. headers: { 'Content-Type': 'application/json' },
  10065. body: JSON.stringify({ disabled: true })
  10066. });
  10067. loadDynamicRouting();
  10068. }
  10069. async function removeSelectedOspfInstance() {
  10070. const id = state.selectedOspfRow?.instances;
  10071. if (!id) return;
  10072. if (!confirm('Delete selected OSPF instance?')) return;
  10073. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10074. loadDynamicRouting();
  10075. }
  10076. async function promptCommentOspfInstance() {
  10077. const id = state.selectedOspfRow?.instances;
  10078. if (!id) return;
  10079. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10080. if (!inst) return;
  10081. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10082. if (comment === null) return;
  10083. inst.comment = comment;
  10084. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10085. method: 'POST',
  10086. headers: { 'Content-Type': 'application/json' },
  10087. body: JSON.stringify(inst)
  10088. });
  10089. loadDynamicRouting();
  10090. }
  10091. // --- 2. OSPF AREA ---
  10092. function populateOspfAreaDropdowns() {
  10093. const instSelect = document.getElementById('modal-ospf-area-instance');
  10094. if (instSelect) {
  10095. const cur = instSelect.value;
  10096. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10097. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10098. if (cur) instSelect.value = cur;
  10099. }
  10100. }
  10101. function openOspfAreaModal(id = null) {
  10102. const isEdit = !!id;
  10103. populateOspfAreaDropdowns();
  10104. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10105. id: '',
  10106. name: 'Default',
  10107. instance: 'Default',
  10108. area_id: '0.0.0.0',
  10109. area_type: 'default',
  10110. default_cost: 1,
  10111. no_summaries: false,
  10112. disabled: false,
  10113. comment: ''
  10114. };
  10115. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10116. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10117. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10118. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10119. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10120. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10121. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10122. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10123. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10124. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10125. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10126. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10127. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10128. }
  10129. function openEditOspfAreaModal(id) {
  10130. openOspfAreaModal(id);
  10131. }
  10132. function closeOspfAreaModal() {
  10133. document.getElementById('ospf-area-modal').classList.add('hidden');
  10134. }
  10135. async function submitOspfArea(e) {
  10136. if (e) e.preventDefault();
  10137. const payload = {
  10138. id: document.getElementById('modal-ospf-area-id').value,
  10139. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10140. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10141. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10142. area_type: document.getElementById('modal-ospf-area-type').value,
  10143. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10144. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10145. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10146. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10147. };
  10148. try {
  10149. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10150. method: 'POST',
  10151. headers: { 'Content-Type': 'application/json' },
  10152. body: JSON.stringify(payload)
  10153. });
  10154. if (res.ok) {
  10155. closeOspfAreaModal();
  10156. showToast('Saved', 'OSPF area saved', 'success');
  10157. loadDynamicRouting();
  10158. } else {
  10159. const err = await res.json();
  10160. showToast('Error', err.error || 'Failed to save area', 'error');
  10161. }
  10162. } catch (err) {
  10163. showToast('Error', err.message, 'error');
  10164. }
  10165. }
  10166. function applyOspfAreaForm() {
  10167. submitOspfArea(null);
  10168. }
  10169. function copyOspfArea() {
  10170. document.getElementById('modal-ospf-area-id').value = '';
  10171. document.getElementById('modal-ospf-area-name').value += '-copy';
  10172. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10173. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10174. }
  10175. async function deleteCurrentOspfArea() {
  10176. const id = document.getElementById('modal-ospf-area-id').value;
  10177. if (!id) return;
  10178. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10179. try {
  10180. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10181. if (res.ok) {
  10182. closeOspfAreaModal();
  10183. showToast('Removed', 'OSPF area deleted', 'success');
  10184. loadDynamicRouting();
  10185. }
  10186. } catch (err) {
  10187. showToast('Error', err.message, 'error');
  10188. }
  10189. }
  10190. async function enableSelectedOspfArea() {
  10191. const id = state.selectedOspfRow?.areas;
  10192. if (!id) return;
  10193. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10194. method: 'POST',
  10195. headers: { 'Content-Type': 'application/json' },
  10196. body: JSON.stringify({ disabled: false })
  10197. });
  10198. loadDynamicRouting();
  10199. }
  10200. async function disableSelectedOspfArea() {
  10201. const id = state.selectedOspfRow?.areas;
  10202. if (!id) return;
  10203. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10204. method: 'POST',
  10205. headers: { 'Content-Type': 'application/json' },
  10206. body: JSON.stringify({ disabled: true })
  10207. });
  10208. loadDynamicRouting();
  10209. }
  10210. async function removeSelectedOspfArea() {
  10211. const id = state.selectedOspfRow?.areas;
  10212. if (!id) return;
  10213. if (!confirm('Delete selected OSPF area?')) return;
  10214. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10215. loadDynamicRouting();
  10216. }
  10217. async function promptCommentOspfArea() {
  10218. const id = state.selectedOspfRow?.areas;
  10219. if (!id) return;
  10220. const area = (state.ospfAreas || []).find(a => a.id === id);
  10221. if (!area) return;
  10222. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10223. if (comment === null) return;
  10224. area.comment = comment;
  10225. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10226. method: 'POST',
  10227. headers: { 'Content-Type': 'application/json' },
  10228. body: JSON.stringify(area)
  10229. });
  10230. loadDynamicRouting();
  10231. }
  10232. // --- 3. OSPF AREA RANGE ---
  10233. function populateAreaRangeDropdowns() {
  10234. const select = document.getElementById('modal-ospf-range-area');
  10235. if (select) {
  10236. const cur = select.value;
  10237. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10238. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10239. if (cur) select.value = cur;
  10240. }
  10241. }
  10242. function openOspfAreaRangeModal(id = null) {
  10243. const isEdit = !!id;
  10244. populateAreaRangeDropdowns();
  10245. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10246. id: '',
  10247. area: 'Default',
  10248. prefix: '',
  10249. cost: 1,
  10250. advertise: true,
  10251. disabled: false,
  10252. comment: ''
  10253. };
  10254. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10255. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10256. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10257. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10258. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10259. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10260. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10261. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10262. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10263. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10264. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10265. }
  10266. function openEditOspfAreaRangeModal(id) {
  10267. openOspfAreaRangeModal(id);
  10268. }
  10269. function closeOspfAreaRangeModal() {
  10270. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10271. }
  10272. async function submitOspfAreaRange(e) {
  10273. if (e) e.preventDefault();
  10274. const payload = {
  10275. id: document.getElementById('modal-ospf-range-id').value,
  10276. area: document.getElementById('modal-ospf-range-area').value,
  10277. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10278. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10279. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10280. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10281. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10282. };
  10283. try {
  10284. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10285. method: 'POST',
  10286. headers: { 'Content-Type': 'application/json' },
  10287. body: JSON.stringify(payload)
  10288. });
  10289. if (res.ok) {
  10290. closeOspfAreaRangeModal();
  10291. showToast('Saved', 'Area range saved', 'success');
  10292. loadDynamicRouting();
  10293. } else {
  10294. const err = await res.json();
  10295. showToast('Error', err.error || 'Failed to save area range', 'error');
  10296. }
  10297. } catch (err) {
  10298. showToast('Error', err.message, 'error');
  10299. }
  10300. }
  10301. function applyOspfAreaRangeForm() {
  10302. submitOspfAreaRange(null);
  10303. }
  10304. async function deleteCurrentOspfAreaRange() {
  10305. const id = document.getElementById('modal-ospf-range-id').value;
  10306. if (!id) return;
  10307. if (!confirm('Delete this area range?')) return;
  10308. try {
  10309. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10310. closeOspfAreaRangeModal();
  10311. showToast('Removed', 'Area range removed', 'success');
  10312. loadDynamicRouting();
  10313. } catch (err) {
  10314. showToast('Error', err.message, 'error');
  10315. }
  10316. }
  10317. async function enableSelectedOspfAreaRange() {
  10318. const id = state.selectedOspfRow?.['area-ranges'];
  10319. if (!id) return;
  10320. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10321. if (!r) return;
  10322. r.disabled = false;
  10323. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10324. loadDynamicRouting();
  10325. }
  10326. async function disableSelectedOspfAreaRange() {
  10327. const id = state.selectedOspfRow?.['area-ranges'];
  10328. if (!id) return;
  10329. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10330. if (!r) return;
  10331. r.disabled = true;
  10332. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10333. loadDynamicRouting();
  10334. }
  10335. async function removeSelectedOspfAreaRange() {
  10336. const id = state.selectedOspfRow?.['area-ranges'];
  10337. if (!id) return;
  10338. if (!confirm('Delete selected area range?')) return;
  10339. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10340. loadDynamicRouting();
  10341. }
  10342. async function promptCommentOspfAreaRange() {
  10343. const id = state.selectedOspfRow?.['area-ranges'];
  10344. if (!id) return;
  10345. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10346. if (!r) return;
  10347. const comment = prompt('Enter comment for area range:', r.comment || '');
  10348. if (comment === null) return;
  10349. r.comment = comment;
  10350. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10351. loadDynamicRouting();
  10352. }
  10353. // --- 4. OSPF INTERFACE TEMPLATE ---
  10354. function switchOspfTemplateTab(tab) {
  10355. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10356. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10357. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10358. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10359. if (tab === 'general') {
  10360. if (tabGen) tabGen.classList.remove('hidden');
  10361. if (tabAuth) tabAuth.classList.add('hidden');
  10362. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10363. 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';
  10364. } else {
  10365. if (tabGen) tabGen.classList.add('hidden');
  10366. if (tabAuth) tabAuth.classList.remove('hidden');
  10367. 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';
  10368. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10369. }
  10370. }
  10371. function populateTemplateAreaDropdowns() {
  10372. const select = document.getElementById('modal-ospf-tmpl-area');
  10373. if (select) {
  10374. const cur = select.value;
  10375. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10376. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10377. if (cur) select.value = cur;
  10378. }
  10379. }
  10380. function openOspfTemplateModal(id = null) {
  10381. const isEdit = !!id;
  10382. populateTemplateAreaDropdowns();
  10383. switchOspfTemplateTab('general');
  10384. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10385. id: '',
  10386. interfaces: '',
  10387. area: 'Default',
  10388. networks: '',
  10389. network_type: 'broadcast',
  10390. cost: 1,
  10391. priority: 128,
  10392. passive: false,
  10393. hello_interval: 10,
  10394. dead_interval: 40,
  10395. auth: 'none',
  10396. auth_key: '',
  10397. disabled: false,
  10398. comment: ''
  10399. };
  10400. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10401. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10402. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10403. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10404. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10405. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10406. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10407. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10408. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10409. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10410. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10411. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10412. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10413. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10414. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10415. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10416. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10417. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10418. }
  10419. function openEditOspfTemplateModal(id) {
  10420. openOspfTemplateModal(id);
  10421. }
  10422. function closeOspfTemplateModal() {
  10423. document.getElementById('ospf-template-modal').classList.add('hidden');
  10424. }
  10425. async function submitOspfTemplate(e) {
  10426. if (e) e.preventDefault();
  10427. const payload = {
  10428. id: document.getElementById('modal-ospf-tmpl-id').value,
  10429. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10430. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10431. area: document.getElementById('modal-ospf-tmpl-area').value,
  10432. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10433. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10434. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10435. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10436. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10437. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10438. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10439. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10440. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10441. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10442. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10443. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10444. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10445. };
  10446. try {
  10447. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10448. method: 'POST',
  10449. headers: { 'Content-Type': 'application/json' },
  10450. body: JSON.stringify(payload)
  10451. });
  10452. if (res.ok) {
  10453. closeOspfTemplateModal();
  10454. showToast('Saved', 'Interface template saved', 'success');
  10455. loadDynamicRouting();
  10456. } else {
  10457. const err = await res.json();
  10458. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10459. }
  10460. } catch (err) {
  10461. showToast('Error', err.message, 'error');
  10462. }
  10463. }
  10464. function applyOspfTemplateForm() {
  10465. submitOspfTemplate(null);
  10466. }
  10467. function copyOspfTemplate() {
  10468. document.getElementById('modal-ospf-tmpl-id').value = '';
  10469. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10470. showToast('Copied', 'Duplicated as new template', 'info');
  10471. }
  10472. async function deleteCurrentOspfTemplate() {
  10473. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10474. if (!id) return;
  10475. if (!confirm('Delete this interface template?')) return;
  10476. try {
  10477. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10478. closeOspfTemplateModal();
  10479. showToast('Removed', 'Interface template deleted', 'success');
  10480. loadDynamicRouting();
  10481. } catch (err) {
  10482. showToast('Error', err.message, 'error');
  10483. }
  10484. }
  10485. async function enableSelectedOspfTemplate() {
  10486. const id = state.selectedOspfRow?.templates;
  10487. if (!id) return;
  10488. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10489. method: 'POST',
  10490. headers: { 'Content-Type': 'application/json' },
  10491. body: JSON.stringify({ disabled: false })
  10492. });
  10493. loadDynamicRouting();
  10494. }
  10495. async function disableSelectedOspfTemplate() {
  10496. const id = state.selectedOspfRow?.templates;
  10497. if (!id) return;
  10498. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10499. method: 'POST',
  10500. headers: { 'Content-Type': 'application/json' },
  10501. body: JSON.stringify({ disabled: true })
  10502. });
  10503. loadDynamicRouting();
  10504. }
  10505. async function removeSelectedOspfTemplate() {
  10506. const id = state.selectedOspfRow?.templates;
  10507. if (!id) return;
  10508. if (!confirm('Delete selected interface template?')) return;
  10509. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10510. loadDynamicRouting();
  10511. }
  10512. async function promptCommentOspfTemplate() {
  10513. const id = state.selectedOspfRow?.templates;
  10514. if (!id) return;
  10515. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10516. if (!tmpl) return;
  10517. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10518. if (comment === null) return;
  10519. tmpl.comment = comment;
  10520. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10521. method: 'POST',
  10522. headers: { 'Content-Type': 'application/json' },
  10523. body: JSON.stringify(tmpl)
  10524. });
  10525. loadDynamicRouting();
  10526. }
  10527. // --- 5. OSPF STATIC NEIGHBOR ---
  10528. function populateStaticNbrAreaDropdowns() {
  10529. const select = document.getElementById('modal-ospf-snbr-area');
  10530. if (select) {
  10531. const cur = select.value;
  10532. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10533. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10534. if (cur) select.value = cur;
  10535. }
  10536. }
  10537. function openOspfStaticNbrModal(id = null) {
  10538. const isEdit = !!id;
  10539. populateStaticNbrAreaDropdowns();
  10540. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10541. id: '',
  10542. address: '',
  10543. area: 'Default',
  10544. poll_interval: 120,
  10545. cost: 1,
  10546. disabled: false,
  10547. comment: ''
  10548. };
  10549. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10550. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10551. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10552. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10553. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10554. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10555. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10556. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10557. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10558. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10559. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10560. }
  10561. function openEditOspfStaticNbrModal(id) {
  10562. openOspfStaticNbrModal(id);
  10563. }
  10564. function closeOspfStaticNbrModal() {
  10565. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10566. }
  10567. async function submitOspfStaticNbr(e) {
  10568. if (e) e.preventDefault();
  10569. const payload = {
  10570. id: document.getElementById('modal-ospf-snbr-id').value,
  10571. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10572. area: document.getElementById('modal-ospf-snbr-area').value,
  10573. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10574. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10575. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10576. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10577. };
  10578. try {
  10579. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10580. method: 'POST',
  10581. headers: { 'Content-Type': 'application/json' },
  10582. body: JSON.stringify(payload)
  10583. });
  10584. if (res.ok) {
  10585. closeOspfStaticNbrModal();
  10586. showToast('Saved', 'Static neighbor saved', 'success');
  10587. loadDynamicRouting();
  10588. } else {
  10589. const err = await res.json();
  10590. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10591. }
  10592. } catch (err) {
  10593. showToast('Error', err.message, 'error');
  10594. }
  10595. }
  10596. function applyOspfStaticNbrForm() {
  10597. submitOspfStaticNbr(null);
  10598. }
  10599. async function deleteCurrentOspfStaticNbr() {
  10600. const id = document.getElementById('modal-ospf-snbr-id').value;
  10601. if (!id) return;
  10602. if (!confirm('Delete this static neighbor?')) return;
  10603. try {
  10604. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10605. closeOspfStaticNbrModal();
  10606. showToast('Removed', 'Static neighbor removed', 'success');
  10607. loadDynamicRouting();
  10608. } catch (err) {
  10609. showToast('Error', err.message, 'error');
  10610. }
  10611. }
  10612. async function enableSelectedOspfStaticNbr() {
  10613. const id = state.selectedOspfRow?.['static-nbrs'];
  10614. if (!id) return;
  10615. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10616. loadDynamicRouting();
  10617. }
  10618. async function disableSelectedOspfStaticNbr() {
  10619. const id = state.selectedOspfRow?.['static-nbrs'];
  10620. if (!id) return;
  10621. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10622. loadDynamicRouting();
  10623. }
  10624. async function removeSelectedOspfStaticNbr() {
  10625. const id = state.selectedOspfRow?.['static-nbrs'];
  10626. if (!id) return;
  10627. if (!confirm('Delete selected static neighbor?')) return;
  10628. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10629. loadDynamicRouting();
  10630. }
  10631. async function promptCommentOspfStaticNbr() {
  10632. const id = state.selectedOspfRow?.['static-nbrs'];
  10633. if (!id) return;
  10634. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10635. if (!n) return;
  10636. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10637. if (comment === null) return;
  10638. n.comment = comment;
  10639. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10640. loadDynamicRouting();
  10641. }
  10642. // Backward-compat aliases
  10643. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10644. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10645. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10646. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10647. function deleteOspfInterface(id) {
  10648. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10649. }
  10650. function toggleOspfInterfaceState(id, disabled) {
  10651. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10652. method: 'POST',
  10653. headers: { 'Content-Type': 'application/json' },
  10654. body: JSON.stringify({ disabled })
  10655. }).then(() => loadDynamicRouting());
  10656. }
  10657. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10658. function deleteOspfArea(id) {
  10659. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10660. }
  10661. // ============================================================================
  10662. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10663. // ============================================================================
  10664. function switchBridgeSubTab(tab) {
  10665. state.bridgeSubTab = tab;
  10666. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10667. tabs.forEach(t => {
  10668. const panel = document.getElementById(`bridge-subtab-${t}`);
  10669. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10670. if (panel) {
  10671. if (t === tab) panel.classList.remove('hidden');
  10672. else panel.classList.add('hidden');
  10673. }
  10674. if (btn) {
  10675. if (t === tab) {
  10676. 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';
  10677. } else {
  10678. 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';
  10679. }
  10680. }
  10681. });
  10682. const addBtn = document.getElementById('bridge-top-action-btn');
  10683. if (addBtn) {
  10684. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10685. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10686. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10687. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10688. }
  10689. if (tab === 'hosts') loadBridgeHosts();
  10690. setTimeout(initTableSorting, 50);
  10691. }
  10692. function openCurrentBridgeModal() {
  10693. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10694. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10695. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10696. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10697. }
  10698. async function loadBridge() {
  10699. try {
  10700. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10701. fetch(`${API_BASE}/bridge/bridges`),
  10702. fetch(`${API_BASE}/bridge/ports`),
  10703. fetch(`${API_BASE}/bridge/vlans`),
  10704. fetch(`${API_BASE}/bridge/summary`),
  10705. fetch(`${API_BASE}/vpn/eoip`),
  10706. fetch(`${API_BASE}/vpn/vxlan`),
  10707. fetch(`${API_BASE}/vlans`)
  10708. ]);
  10709. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10710. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10711. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10712. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10713. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10714. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10715. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10716. // Badges & Stats
  10717. const bBridges = document.getElementById('bridge-badge-bridges');
  10718. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10719. const bPorts = document.getElementById('bridge-badge-ports');
  10720. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10721. const bVlans = document.getElementById('bridge-badge-vlans');
  10722. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10723. const bHosts = document.getElementById('bridge-badge-hosts');
  10724. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10725. const sBr = document.getElementById('bridge-stat-bridges');
  10726. if (sBr) sBr.innerText = (state.bridges || []).length;
  10727. const sPorts = document.getElementById('bridge-stat-ports');
  10728. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10729. const sHosts = document.getElementById('bridge-stat-hosts');
  10730. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10731. renderBridges();
  10732. renderBridgePorts();
  10733. renderBridgeVLANs();
  10734. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10735. } catch (err) {
  10736. console.error('Failed to load bridge subsystem:', err);
  10737. }
  10738. }
  10739. // ----------------- Bridges -----------------
  10740. function renderBridges() {
  10741. const tbody = document.getElementById('bridge-table-body');
  10742. const empty = document.getElementById('bridge-empty-bridges');
  10743. const countBadge = document.getElementById('bridge-count-badge');
  10744. if (!tbody) return;
  10745. tbody.innerHTML = '';
  10746. const bridges = state.bridges || [];
  10747. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10748. if (bridges.length === 0) {
  10749. empty?.classList.remove('hidden');
  10750. return;
  10751. }
  10752. empty?.classList.add('hidden');
  10753. bridges.forEach((b, idx) => {
  10754. const tr = document.createElement('tr');
  10755. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10756. // Format IP addresses pill list
  10757. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10758. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10759. ipsHtml = b.ip_addresses.map(ip => `
  10760. <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">
  10761. <span>${ip}</span>
  10762. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10763. </span>
  10764. `).join(' ');
  10765. }
  10766. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10767. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10768. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10769. tr.innerHTML = `
  10770. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10771. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10772. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10773. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10774. </td>
  10775. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10776. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10777. <td class="py-2.5 px-3">
  10778. <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>
  10779. </td>
  10780. <td class="py-2.5 px-3 text-center">
  10781. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10782. </td>
  10783. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10784. <td class="py-2.5 px-3">
  10785. <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>
  10786. </td>
  10787. <td class="py-2.5 px-3">
  10788. <div class="flex items-center gap-1.5 flex-wrap">
  10789. ${ipsHtml}
  10790. <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>
  10791. </div>
  10792. </td>
  10793. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10794. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10795. </td>
  10796. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10797. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10798. <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>
  10799. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10800. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10801. </td>
  10802. `;
  10803. tbody.appendChild(tr);
  10804. });
  10805. }
  10806. function openAddBridgeModal() {
  10807. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10808. document.getElementById('bridge-modal-id').value = '';
  10809. document.getElementById('bridge-modal-name').value = 'bridge1';
  10810. document.getElementById('bridge-modal-name').disabled = false;
  10811. document.getElementById('bridge-modal-mtu').value = '1500';
  10812. document.getElementById('bridge-modal-mac').value = '';
  10813. document.getElementById('bridge-modal-stp').value = 'stp';
  10814. document.getElementById('bridge-modal-priority').value = '32768';
  10815. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10816. document.getElementById('bridge-modal-pvid').value = '1';
  10817. document.getElementById('bridge-modal-fastforward').checked = true;
  10818. document.getElementById('bridge-modal-comment').value = '';
  10819. document.getElementById('bridge-modal-disabled').checked = false;
  10820. toggleBridgeModalVlanFiltering();
  10821. document.getElementById('bridge-modal').classList.remove('hidden');
  10822. }
  10823. function openEditBridgeModal(id) {
  10824. const b = (state.bridges || []).find(x => x.id === id);
  10825. if (!b) return;
  10826. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10827. document.getElementById('bridge-modal-id').value = b.id;
  10828. document.getElementById('bridge-modal-name').value = b.name;
  10829. document.getElementById('bridge-modal-name').disabled = true;
  10830. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10831. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10832. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10833. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10834. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10835. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10836. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10837. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10838. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10839. toggleBridgeModalVlanFiltering();
  10840. document.getElementById('bridge-modal').classList.remove('hidden');
  10841. }
  10842. function closeBridgeModal() {
  10843. document.getElementById('bridge-modal').classList.add('hidden');
  10844. }
  10845. function toggleBridgeModalVlanFiltering() {
  10846. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10847. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10848. if (pvidBox) {
  10849. if (chk) pvidBox.classList.remove('opacity-40');
  10850. else pvidBox.classList.add('opacity-40');
  10851. }
  10852. }
  10853. async function submitSaveBridge(e) {
  10854. e.preventDefault();
  10855. const id = document.getElementById('bridge-modal-id').value;
  10856. const name = document.getElementById('bridge-modal-name').value.trim();
  10857. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10858. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10859. const stp = document.getElementById('bridge-modal-stp').value;
  10860. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10861. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10862. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10863. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10864. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10865. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10866. try {
  10867. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10868. method: 'POST',
  10869. headers: { 'Content-Type': 'application/json' },
  10870. body: JSON.stringify({
  10871. id,
  10872. name,
  10873. mtu,
  10874. mac_address: mac,
  10875. stp,
  10876. priority,
  10877. vlan_filtering: vlanFiltering,
  10878. pvid,
  10879. fast_forward: fastForward,
  10880. comment,
  10881. disabled
  10882. })
  10883. });
  10884. if (res.ok) {
  10885. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10886. closeBridgeModal();
  10887. loadBridge();
  10888. fetchData(false);
  10889. } else {
  10890. const err = await res.json();
  10891. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10892. }
  10893. } catch (err) {
  10894. showToast('Error', err.message, 'error');
  10895. }
  10896. }
  10897. async function toggleBridgeState(id, disabled) {
  10898. try {
  10899. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10900. method: 'POST',
  10901. headers: { 'Content-Type': 'application/json' },
  10902. body: JSON.stringify({ disabled })
  10903. });
  10904. if (res.ok) {
  10905. loadBridge();
  10906. fetchData(false);
  10907. }
  10908. } catch (err) {
  10909. showToast('Error', err.message, 'error');
  10910. }
  10911. }
  10912. async function deleteBridge(id) {
  10913. const b = (state.bridges || []).find(x => x.id === id);
  10914. const name = b ? b.name : id;
  10915. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10916. try {
  10917. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10918. if (res.ok) {
  10919. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10920. loadBridge();
  10921. fetchData(false);
  10922. } else {
  10923. const err = await res.json();
  10924. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10925. }
  10926. } catch (err) {
  10927. showToast('Error', err.message, 'error');
  10928. }
  10929. }
  10930. // ----------------- Bridge IP Assignments -----------------
  10931. function openAddBridgeIPModal(id, name) {
  10932. document.getElementById('bridge-ip-modal-id').value = id;
  10933. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10934. document.getElementById('bridge-ip-modal-cidr').value = '';
  10935. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10936. }
  10937. function closeBridgeIPModal() {
  10938. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10939. }
  10940. async function submitAddBridgeIP(e) {
  10941. e.preventDefault();
  10942. const id = document.getElementById('bridge-ip-modal-id').value;
  10943. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10944. try {
  10945. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10946. method: 'POST',
  10947. headers: { 'Content-Type': 'application/json' },
  10948. body: JSON.stringify({ ip })
  10949. });
  10950. if (res.ok) {
  10951. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10952. closeBridgeIPModal();
  10953. loadBridge();
  10954. fetchData(false);
  10955. } else {
  10956. const err = await res.json();
  10957. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10958. }
  10959. } catch (err) {
  10960. showToast('Error', err.message, 'error');
  10961. }
  10962. }
  10963. async function deleteBridgeIP(id, ip) {
  10964. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10965. try {
  10966. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10967. method: 'DELETE',
  10968. headers: { 'Content-Type': 'application/json' },
  10969. body: JSON.stringify({ ip })
  10970. });
  10971. if (res.ok) {
  10972. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10973. loadBridge();
  10974. fetchData(false);
  10975. }
  10976. } catch (err) {
  10977. showToast('Error', err.message, 'error');
  10978. }
  10979. }
  10980. // ----------------- Bridge Ports -----------------
  10981. function renderBridgePorts() {
  10982. const tbody = document.getElementById('bridge-ports-table-body');
  10983. const empty = document.getElementById('bridge-empty-ports');
  10984. const countBadge = document.getElementById('bridge-ports-count-badge');
  10985. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10986. if (!tbody) return;
  10987. tbody.innerHTML = '';
  10988. // Update filter select
  10989. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10990. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10991. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10992. if (ports.length === 0) {
  10993. empty?.classList.remove('hidden');
  10994. return;
  10995. }
  10996. empty?.classList.add('hidden');
  10997. ports.forEach((p, idx) => {
  10998. const tr = document.createElement('tr');
  10999. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11000. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11001. tr.innerHTML = `
  11002. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11003. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11004. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11005. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11006. </td>
  11007. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11008. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11009. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11010. <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>
  11011. <td class="py-2.5 px-3">
  11012. ${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>'}
  11013. </td>
  11014. <td class="py-2.5 px-3">
  11015. <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>
  11016. </td>
  11017. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11018. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11019. <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>
  11020. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11021. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11022. </td>
  11023. `;
  11024. tbody.appendChild(tr);
  11025. });
  11026. }
  11027. function openAddBridgePortModal() {
  11028. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11029. document.getElementById('bridge-port-modal-id').value = '';
  11030. populateBridgeSelect('bridge-port-modal-bridge');
  11031. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11032. document.getElementById('bridge-port-modal-pvid').value = '1';
  11033. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11034. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11035. document.getElementById('bridge-port-modal-horizon').value = '0';
  11036. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11037. document.getElementById('bridge-port-modal-priority').value = '128';
  11038. document.getElementById('bridge-port-modal-learn').checked = true;
  11039. document.getElementById('bridge-port-modal-comment').value = '';
  11040. document.getElementById('bridge-port-modal-disabled').checked = false;
  11041. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11042. }
  11043. function openEditBridgePortModal(id) {
  11044. const p = (state.bridgePorts || []).find(x => x.id === id);
  11045. if (!p) return;
  11046. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11047. document.getElementById('bridge-port-modal-id').value = p.id;
  11048. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11049. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11050. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11051. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11052. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11053. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11054. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11055. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11056. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11057. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11058. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11059. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11060. }
  11061. function closeBridgePortModal() {
  11062. document.getElementById('bridge-port-modal').classList.add('hidden');
  11063. }
  11064. async function submitSaveBridgePort(e) {
  11065. e.preventDefault();
  11066. const id = document.getElementById('bridge-port-modal-id').value;
  11067. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11068. const iface = document.getElementById('bridge-port-modal-interface').value;
  11069. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11070. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11071. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11072. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11073. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11074. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11075. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11076. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11077. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11078. try {
  11079. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11080. method: 'POST',
  11081. headers: { 'Content-Type': 'application/json' },
  11082. body: JSON.stringify({
  11083. id,
  11084. bridge,
  11085. interface: iface,
  11086. pvid,
  11087. frame_types: frameTypes,
  11088. ingress_filtering: ingressFiltering,
  11089. horizon,
  11090. path_cost: pathCost,
  11091. priority,
  11092. learn,
  11093. comment,
  11094. disabled
  11095. })
  11096. });
  11097. if (res.ok) {
  11098. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11099. closeBridgePortModal();
  11100. loadBridge();
  11101. fetchData(false);
  11102. } else {
  11103. const err = await res.json();
  11104. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11105. }
  11106. } catch (err) {
  11107. showToast('Error', err.message, 'error');
  11108. }
  11109. }
  11110. async function toggleBridgePortState(id, disabled) {
  11111. try {
  11112. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11113. method: 'POST',
  11114. headers: { 'Content-Type': 'application/json' },
  11115. body: JSON.stringify({ disabled })
  11116. });
  11117. if (res.ok) {
  11118. loadBridge();
  11119. fetchData(false);
  11120. }
  11121. } catch (err) {
  11122. showToast('Error', err.message, 'error');
  11123. }
  11124. }
  11125. async function deleteBridgePort(id) {
  11126. const p = (state.bridgePorts || []).find(x => x.id === id);
  11127. const iface = p ? p.interface : id;
  11128. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11129. try {
  11130. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11131. if (res.ok) {
  11132. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11133. loadBridge();
  11134. fetchData(false);
  11135. }
  11136. } catch (err) {
  11137. showToast('Error', err.message, 'error');
  11138. }
  11139. }
  11140. // ----------------- Bridge VLANs -----------------
  11141. function renderBridgeVLANs() {
  11142. const tbody = document.getElementById('bridge-vlans-table-body');
  11143. const empty = document.getElementById('bridge-empty-vlans');
  11144. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11145. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11146. if (!tbody) return;
  11147. tbody.innerHTML = '';
  11148. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11149. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11150. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11151. if (vlans.length === 0) {
  11152. empty?.classList.remove('hidden');
  11153. return;
  11154. }
  11155. empty?.classList.add('hidden');
  11156. vlans.forEach((v, idx) => {
  11157. const tr = document.createElement('tr');
  11158. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11159. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11160. ? 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(' ')
  11161. : '<span class="text-slate-600">none</span>';
  11162. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11163. ? 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(' ')
  11164. : '<span class="text-slate-600">none</span>';
  11165. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11166. tr.innerHTML = `
  11167. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11168. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11169. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11170. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11171. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11172. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11173. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11174. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11175. <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>
  11176. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11177. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11178. </td>
  11179. `;
  11180. tbody.appendChild(tr);
  11181. });
  11182. }
  11183. function openAddBridgeVLANModal() {
  11184. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11185. document.getElementById('bridge-vlan-modal-id').value = '';
  11186. populateBridgeSelect('bridge-vlan-modal-bridge');
  11187. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11188. document.getElementById('bridge-vlan-modal-comment').value = '';
  11189. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11190. updateBridgeVlanPortCheckboxes();
  11191. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11192. }
  11193. function openEditBridgeVLANModal(id) {
  11194. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11195. if (!v) return;
  11196. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11197. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11198. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11199. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11200. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11201. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11202. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11203. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11204. }
  11205. function closeBridgeVlanModal() {
  11206. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11207. }
  11208. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11209. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11210. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11211. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11212. if (!taggedBox || !untaggedBox) return;
  11213. // Ports belonging to the selected bridge
  11214. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11215. if (memberPorts.length === 0) {
  11216. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11217. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11218. return;
  11219. }
  11220. taggedBox.innerHTML = memberPorts.map(p => `
  11221. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11222. <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">
  11223. <span>${p.interface}</span>
  11224. </label>
  11225. `).join('');
  11226. untaggedBox.innerHTML = memberPorts.map(p => `
  11227. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11228. <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">
  11229. <span>${p.interface}</span>
  11230. </label>
  11231. `).join('');
  11232. }
  11233. async function submitSaveBridgeVLAN(e) {
  11234. e.preventDefault();
  11235. const id = document.getElementById('bridge-vlan-modal-id').value;
  11236. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11237. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11238. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11239. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11240. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11241. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11242. try {
  11243. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11244. method: 'POST',
  11245. headers: { 'Content-Type': 'application/json' },
  11246. body: JSON.stringify({
  11247. id,
  11248. bridge,
  11249. vlan_ids: vlanIDs,
  11250. tagged,
  11251. untagged,
  11252. comment,
  11253. disabled
  11254. })
  11255. });
  11256. if (res.ok) {
  11257. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11258. closeBridgeVlanModal();
  11259. loadBridge();
  11260. } else {
  11261. const err = await res.json();
  11262. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11263. }
  11264. } catch (err) {
  11265. showToast('Error', err.message, 'error');
  11266. }
  11267. }
  11268. async function toggleBridgeVLANState(id, disabled) {
  11269. try {
  11270. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11271. method: 'POST',
  11272. headers: { 'Content-Type': 'application/json' },
  11273. body: JSON.stringify({ disabled })
  11274. });
  11275. if (res.ok) loadBridge();
  11276. } catch (err) {
  11277. showToast('Error', err.message, 'error');
  11278. }
  11279. }
  11280. async function deleteBridgeVLAN(id) {
  11281. if (!confirm('Delete this bridge VLAN entry?')) return;
  11282. try {
  11283. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11284. if (res.ok) {
  11285. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11286. loadBridge();
  11287. }
  11288. } catch (err) {
  11289. showToast('Error', err.message, 'error');
  11290. }
  11291. }
  11292. // ----------------- Hosts / MAC Table -----------------
  11293. async function loadBridgeHosts() {
  11294. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11295. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11296. try {
  11297. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11298. const res = await fetch(url);
  11299. if (res.ok) {
  11300. state.bridgeHosts = await res.json();
  11301. renderBridgeHosts();
  11302. }
  11303. } catch (err) {
  11304. console.error('Failed to load bridge hosts:', err);
  11305. }
  11306. }
  11307. function renderBridgeHosts() {
  11308. const tbody = document.getElementById('bridge-hosts-table-body');
  11309. const empty = document.getElementById('bridge-empty-hosts');
  11310. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11311. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11312. if (!tbody) return;
  11313. tbody.innerHTML = '';
  11314. const hosts = (state.bridgeHosts || []).filter(h => {
  11315. if (!search) return true;
  11316. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11317. });
  11318. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11319. if (hosts.length === 0) {
  11320. empty?.classList.remove('hidden');
  11321. return;
  11322. }
  11323. empty?.classList.add('hidden');
  11324. hosts.forEach(h => {
  11325. const tr = document.createElement('tr');
  11326. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11327. let flagBadges = '';
  11328. 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>';
  11329. 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>';
  11330. 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>';
  11331. tr.innerHTML = `
  11332. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11333. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11334. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11335. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11336. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11337. <td class="py-2.5 px-3">${flagBadges}</td>
  11338. `;
  11339. tbody.appendChild(tr);
  11340. });
  11341. }
  11342. async function flushBridgeHosts() {
  11343. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11344. if (!selBridge) {
  11345. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11346. return;
  11347. }
  11348. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11349. try {
  11350. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11351. method: 'POST',
  11352. headers: { 'Content-Type': 'application/json' },
  11353. body: JSON.stringify({ bridge: selBridge })
  11354. });
  11355. if (res.ok) {
  11356. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11357. loadBridgeHosts();
  11358. }
  11359. } catch (err) {
  11360. showToast('Error', err.message, 'error');
  11361. }
  11362. }
  11363. // ----------------- Helpers -----------------
  11364. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11365. const sel = document.getElementById(selectId);
  11366. if (!sel) return;
  11367. const prevVal = currentVal || sel.value;
  11368. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11369. (state.bridges || []).forEach(b => {
  11370. const opt = document.createElement('option');
  11371. opt.value = b.name;
  11372. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11373. if (b.name === prevVal) opt.selected = true;
  11374. sel.appendChild(opt);
  11375. });
  11376. }
  11377. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11378. const sel = document.getElementById(selectId);
  11379. if (!sel) return;
  11380. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11381. // 1. Physical Interfaces
  11382. const grpPhys = document.createElement('optgroup');
  11383. grpPhys.label = 'Physical Interfaces';
  11384. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11385. const opt = document.createElement('option');
  11386. opt.value = i.name;
  11387. opt.innerText = `${i.name} (${i.role || i.type})`;
  11388. if (i.name === currentVal) opt.selected = true;
  11389. grpPhys.appendChild(opt);
  11390. });
  11391. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11392. // 2. VLAN Sub-interfaces
  11393. const grpVlans = document.createElement('optgroup');
  11394. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11395. (state.vlans || []).forEach(v => {
  11396. const opt = document.createElement('option');
  11397. opt.value = v.name;
  11398. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11399. if (v.name === currentVal) opt.selected = true;
  11400. grpVlans.appendChild(opt);
  11401. });
  11402. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11403. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11404. const grpEoip = document.createElement('optgroup');
  11405. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11406. (state.eoipTunnels || []).forEach(t => {
  11407. const opt = document.createElement('option');
  11408. opt.value = t.name;
  11409. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11410. if (t.name === currentVal) opt.selected = true;
  11411. grpEoip.appendChild(opt);
  11412. });
  11413. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11414. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11415. const grpVxlan = document.createElement('optgroup');
  11416. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11417. (state.vxlanTunnels || []).forEach(t => {
  11418. const opt = document.createElement('option');
  11419. opt.value = t.name;
  11420. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11421. if (t.name === currentVal) opt.selected = true;
  11422. grpVxlan.appendChild(opt);
  11423. });
  11424. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11425. }
  11426. // -------------------------------------------------------------
  11427. // DebTik Routing Filters Management (/routing filter)
  11428. // -------------------------------------------------------------
  11429. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11430. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11431. if (!state.rfSort) state.rfSort = {};
  11432. function switchRoutingFilterTab(tab) {
  11433. state.activeRoutingFilterTab = tab;
  11434. const tabs = ['rules', 'community-lists', 'as-lists'];
  11435. tabs.forEach(t => {
  11436. const btn = document.getElementById(`tab-rf-${t}`);
  11437. const content = document.getElementById(`tab-content-rf-${t}`);
  11438. if (btn) {
  11439. if (t === tab) {
  11440. 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';
  11441. } else {
  11442. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11443. }
  11444. }
  11445. if (content) {
  11446. if (t === tab) content.classList.remove('hidden');
  11447. else content.classList.add('hidden');
  11448. }
  11449. });
  11450. const chainContainer = document.getElementById('rf-chain-filter-container');
  11451. if (chainContainer) {
  11452. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11453. else chainContainer.classList.add('hidden');
  11454. }
  11455. renderRoutingFilters();
  11456. }
  11457. function selectFilterRow(tab, id) {
  11458. if (state.selectedFilterRow[tab] === id) {
  11459. delete state.selectedFilterRow[tab];
  11460. } else {
  11461. state.selectedFilterRow[tab] = id;
  11462. }
  11463. if (tab === 'rules') renderRoutingFilterRules();
  11464. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11465. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11466. }
  11467. function openRoutingFilterNewModal() {
  11468. const tab = state.activeRoutingFilterTab || 'rules';
  11469. if (tab === 'rules') openAddRoutingFilterModal();
  11470. else if (tab === 'community-lists') openAddCommunityListModal();
  11471. else if (tab === 'as-lists') openAddASListModal();
  11472. }
  11473. function toggleSelectedRoutingFilter(disabled) {
  11474. const tab = state.activeRoutingFilterTab || 'rules';
  11475. const id = state.selectedFilterRow[tab];
  11476. if (!id) {
  11477. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11478. return;
  11479. }
  11480. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11481. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11482. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11483. }
  11484. function removeSelectedRoutingFilter() {
  11485. const tab = state.activeRoutingFilterTab || 'rules';
  11486. const id = state.selectedFilterRow[tab];
  11487. if (!id) {
  11488. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11489. return;
  11490. }
  11491. if (tab === 'rules') deleteRoutingFilter(id);
  11492. else if (tab === 'community-lists') deleteCommunityList(id);
  11493. else if (tab === 'as-lists') deleteASList(id);
  11494. }
  11495. function searchRoutingFilters(q) {
  11496. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11497. renderRoutingFilters();
  11498. }
  11499. function sortFilterTable(tab, col) {
  11500. if (!state.rfSort) state.rfSort = {};
  11501. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11502. if (state.rfSort[tab].col === col) {
  11503. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11504. } else {
  11505. state.rfSort[tab].col = col;
  11506. state.rfSort[tab].asc = true;
  11507. }
  11508. const asc = state.rfSort[tab].asc;
  11509. let list = [];
  11510. if (tab === 'rules') list = state.routingFilters || [];
  11511. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11512. else if (tab === 'as-lists') list = state.routingASLists || [];
  11513. list.sort((a, b) => {
  11514. let valA = a[col] ?? '';
  11515. let valB = b[col] ?? '';
  11516. if (col === 'flags') {
  11517. valA = a.disabled ? 'X' : 'A';
  11518. valB = b.disabled ? 'X' : 'A';
  11519. }
  11520. if (typeof valA === 'number' && typeof valB === 'number') {
  11521. return asc ? valA - valB : valB - valA;
  11522. }
  11523. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11524. });
  11525. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11526. allCols.forEach(c => {
  11527. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11528. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11529. });
  11530. if (tab === 'rules') renderRoutingFilterRules();
  11531. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11532. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11533. }
  11534. function renderRoutingFilters() {
  11535. const navBadge = document.getElementById('badge-filters-count');
  11536. const allRules = state.routingFilters || [];
  11537. if (navBadge) navBadge.innerText = allRules.length;
  11538. // Populate chain filter select options and datalist
  11539. const chainSelect = document.getElementById('routing-filter-chain-select');
  11540. const chainDatalist = document.getElementById('dl-routing-chains');
  11541. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11542. if (chainSelect) {
  11543. const currentVal = state.filterChainSelected || 'all';
  11544. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11545. uniqueChains.map(ch => {
  11546. const count = allRules.filter(r => r.chain === ch).length;
  11547. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11548. }).join('');
  11549. chainSelect.value = currentVal;
  11550. }
  11551. if (chainDatalist) {
  11552. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11553. }
  11554. renderRoutingFilterRules();
  11555. renderRoutingFilterCommunityLists();
  11556. renderRoutingFilterASLists();
  11557. }
  11558. function filterRoutingFiltersByChain(chain) {
  11559. state.filterChainSelected = chain;
  11560. renderRoutingFilters();
  11561. }
  11562. // -------------------------------------------------------------
  11563. // TAB 1: RULES (/routing filter rule)
  11564. // -------------------------------------------------------------
  11565. function renderRoutingFilterRules() {
  11566. const tbody = document.getElementById('routing-filter-rules-tbody');
  11567. if (!tbody) return;
  11568. const empty = document.getElementById('rf-rules-empty');
  11569. const statusCount = document.getElementById('rf-status-count');
  11570. let list = (state.routingFilters || []).slice();
  11571. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11572. list = list.filter(r => r.chain === state.filterChainSelected);
  11573. }
  11574. const q = state.rfSearchQuery;
  11575. if (q) {
  11576. list = list.filter(r =>
  11577. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11578. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11579. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11580. (r.comment && r.comment.toLowerCase().includes(q))
  11581. );
  11582. }
  11583. if (!state.rfSort?.['rules']) {
  11584. list.sort((a, b) => {
  11585. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11586. return (a.rule_order || 0) - (b.rule_order || 0);
  11587. });
  11588. }
  11589. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11590. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11591. }
  11592. if (list.length === 0) {
  11593. tbody.innerHTML = '';
  11594. if (empty) empty.classList.remove('hidden');
  11595. return;
  11596. }
  11597. if (empty) empty.classList.add('hidden');
  11598. tbody.innerHTML = list.map(r => {
  11599. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11600. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11601. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11602. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11603. let ruleDisplay = '';
  11604. if (r.rule && r.rule.trim() !== '') {
  11605. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11606. } else {
  11607. let conds = [];
  11608. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11609. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11610. let act = r.action || 'accept';
  11611. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11612. }
  11613. return `
  11614. <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'}">
  11615. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11616. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11617. <td class="py-2 px-3">
  11618. <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>
  11619. </td>
  11620. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11621. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11622. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11623. <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>
  11624. <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>
  11625. <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'}">
  11626. ${r.disabled ? 'Enable' : 'Disable'}
  11627. </button>
  11628. <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">
  11629. Edit
  11630. </button>
  11631. <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">
  11632. ✕
  11633. </button>
  11634. </td>
  11635. </tr>
  11636. `;
  11637. }).join('');
  11638. }
  11639. // -------------------------------------------------------------
  11640. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11641. // -------------------------------------------------------------
  11642. function renderRoutingFilterCommunityLists() {
  11643. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11644. if (!tbody) return;
  11645. const empty = document.getElementById('rf-comm-lists-empty');
  11646. const statusCount = document.getElementById('rf-status-count');
  11647. let list = (state.routingCommunityLists || []).slice();
  11648. const q = state.rfSearchQuery;
  11649. if (q) {
  11650. list = list.filter(cl =>
  11651. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11652. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11653. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11654. );
  11655. }
  11656. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11657. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11658. }
  11659. if (list.length === 0) {
  11660. tbody.innerHTML = '';
  11661. if (empty) empty.classList.remove('hidden');
  11662. return;
  11663. }
  11664. if (empty) empty.classList.add('hidden');
  11665. tbody.innerHTML = list.map(cl => {
  11666. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11667. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11668. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11669. const commBadges = (cl.communities || []).map(c =>
  11670. `<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>`
  11671. ).join(' ');
  11672. return `
  11673. <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'}">
  11674. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11675. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11676. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11677. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11678. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11679. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11680. <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'}">
  11681. ${cl.disabled ? 'Enable' : 'Disable'}
  11682. </button>
  11683. <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">
  11684. Edit
  11685. </button>
  11686. <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">
  11687. ✕
  11688. </button>
  11689. </td>
  11690. </tr>
  11691. `;
  11692. }).join('');
  11693. }
  11694. // -------------------------------------------------------------
  11695. // TAB 4: AS LISTS (/routing filter num-list)
  11696. // -------------------------------------------------------------
  11697. function renderRoutingFilterASLists() {
  11698. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11699. if (!tbody) return;
  11700. const empty = document.getElementById('rf-as-lists-empty');
  11701. const statusCount = document.getElementById('rf-status-count');
  11702. let list = (state.routingASLists || []).slice();
  11703. const q = state.rfSearchQuery;
  11704. if (q) {
  11705. list = list.filter(al =>
  11706. (al.name && al.name.toLowerCase().includes(q)) ||
  11707. (al.range && al.range.toLowerCase().includes(q)) ||
  11708. (al.comment && al.comment.toLowerCase().includes(q))
  11709. );
  11710. }
  11711. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11712. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11713. }
  11714. if (list.length === 0) {
  11715. tbody.innerHTML = '';
  11716. if (empty) empty.classList.remove('hidden');
  11717. return;
  11718. }
  11719. if (empty) empty.classList.add('hidden');
  11720. tbody.innerHTML = list.map(al => {
  11721. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11722. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11723. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11724. return `
  11725. <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'}">
  11726. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11727. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11728. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11729. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11730. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11731. <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'}">
  11732. ${al.disabled ? 'Enable' : 'Disable'}
  11733. </button>
  11734. <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">
  11735. Edit
  11736. </button>
  11737. <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">
  11738. ✕
  11739. </button>
  11740. </td>
  11741. </tr>
  11742. `;
  11743. }).join('');
  11744. }
  11745. // -------------------------------------------------------------
  11746. // SNIPPETS & WIZARD HELPERS
  11747. // -------------------------------------------------------------
  11748. function insertRuleSnippet(type) {
  11749. const textarea = document.getElementById('modal-rf-rule');
  11750. if (!textarea) return;
  11751. let snippet = '';
  11752. switch (type) {
  11753. case 'accept-default':
  11754. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11755. break;
  11756. case 'drop-rfc1918':
  11757. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11758. break;
  11759. case 'len-24':
  11760. snippet = 'if (dst-len > 24) { reject; }';
  11761. break;
  11762. case 'local-pref-150':
  11763. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11764. break;
  11765. case 'as-prepend-2':
  11766. snippet = 'set bgp-path-prepend 2; accept;';
  11767. break;
  11768. case 'set-comm':
  11769. snippet = 'set bgp-communities.add 65000:100; accept;';
  11770. break;
  11771. case 'match-comm':
  11772. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11773. break;
  11774. case 'reject-all':
  11775. snippet = 'reject;';
  11776. break;
  11777. }
  11778. if (!snippet) return;
  11779. if (!textarea.value.trim()) {
  11780. textarea.value = snippet;
  11781. } else {
  11782. textarea.value = textarea.value.trim() + '\n' + snippet;
  11783. }
  11784. }
  11785. function generateScriptFromWizard() {
  11786. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11787. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11788. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11789. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11790. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11791. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11792. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11793. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11794. const conds = [];
  11795. if (pfx) {
  11796. if (pfxLen) {
  11797. if (pfxLen.includes('-')) {
  11798. const parts = pfxLen.split('-');
  11799. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11800. } else {
  11801. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11802. }
  11803. } else {
  11804. conds.push(`dst in ${pfx}`);
  11805. }
  11806. }
  11807. if (proto && proto !== 'any') {
  11808. conds.push(`protocol ${proto}`);
  11809. }
  11810. if (asp) {
  11811. conds.push(`bgp-as-path "${asp}"`);
  11812. }
  11813. if (comm) {
  11814. conds.push(`bgp-communities includes ${comm}`);
  11815. }
  11816. const actions = [];
  11817. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11818. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11819. if (act && act !== 'passthrough') {
  11820. actions.push(`${act};`);
  11821. }
  11822. let code = '';
  11823. if (conds.length > 0) {
  11824. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11825. } else {
  11826. code = actions.join(' ');
  11827. }
  11828. const textarea = document.getElementById('modal-rf-rule');
  11829. if (textarea) textarea.value = code;
  11830. }
  11831. // -------------------------------------------------------------
  11832. // MODAL CRUD: RULES (/routing filter rule)
  11833. // -------------------------------------------------------------
  11834. function openAddRoutingFilterModal(defaultChain = '') {
  11835. const form = document.getElementById('routing-filter-form');
  11836. if (form) form.reset();
  11837. const idEl = document.getElementById('modal-rf-id');
  11838. if (idEl) idEl.value = '';
  11839. const titleEl = document.getElementById('modal-rf-title');
  11840. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11841. const chainEl = document.getElementById('modal-rf-chain');
  11842. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11843. const orderEl = document.getElementById('modal-rf-order');
  11844. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11845. const ruleEl = document.getElementById('modal-rf-rule');
  11846. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11847. const disEl = document.getElementById('modal-rf-disabled');
  11848. if (disEl) disEl.checked = false;
  11849. const modal = document.getElementById('modal-routing-filter');
  11850. if (modal) modal.classList.remove('hidden');
  11851. }
  11852. function openEditRoutingFilterModal(id) {
  11853. const r = (state.routingFilters || []).find(item => item.id === id);
  11854. if (!r) return;
  11855. const idEl = document.getElementById('modal-rf-id');
  11856. if (idEl) idEl.value = r.id;
  11857. const titleEl = document.getElementById('modal-rf-title');
  11858. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11859. const chainEl = document.getElementById('modal-rf-chain');
  11860. if (chainEl) chainEl.value = r.chain || '';
  11861. const orderEl = document.getElementById('modal-rf-order');
  11862. if (orderEl) orderEl.value = r.rule_order || 10;
  11863. const ruleEl = document.getElementById('modal-rf-rule');
  11864. if (ruleEl) {
  11865. if (r.rule) {
  11866. ruleEl.value = r.rule;
  11867. } else {
  11868. let conds = [];
  11869. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11870. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11871. let act = r.action || 'accept';
  11872. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11873. }
  11874. }
  11875. const comEl = document.getElementById('modal-rf-comment');
  11876. if (comEl) comEl.value = r.comment || '';
  11877. const disEl = document.getElementById('modal-rf-disabled');
  11878. if (disEl) disEl.checked = !!r.disabled;
  11879. const modal = document.getElementById('modal-routing-filter');
  11880. if (modal) modal.classList.remove('hidden');
  11881. }
  11882. function closeRoutingFilterModal() {
  11883. const modal = document.getElementById('modal-routing-filter');
  11884. if (modal) modal.classList.add('hidden');
  11885. }
  11886. async function submitRoutingFilter(e) {
  11887. if (e) e.preventDefault();
  11888. const payload = {
  11889. id: document.getElementById('modal-rf-id').value,
  11890. chain: document.getElementById('modal-rf-chain').value.trim(),
  11891. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11892. rule: document.getElementById('modal-rf-rule').value.trim(),
  11893. comment: document.getElementById('modal-rf-comment').value.trim(),
  11894. disabled: document.getElementById('modal-rf-disabled').checked
  11895. };
  11896. try {
  11897. const res = await fetch(`${API_BASE}/routing/filters`, {
  11898. method: 'POST',
  11899. headers: { 'Content-Type': 'application/json' },
  11900. body: JSON.stringify(payload)
  11901. });
  11902. if (res.ok) {
  11903. closeRoutingFilterModal();
  11904. showToast('Success', 'Routing filter rule saved', 'success');
  11905. loadDynamicRouting();
  11906. } else {
  11907. const err = await res.json();
  11908. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11909. }
  11910. } catch (err) {
  11911. showToast('Error', err.message, 'error');
  11912. }
  11913. }
  11914. async function applyRoutingFilterForm() {
  11915. const payload = {
  11916. id: document.getElementById('modal-rf-id').value,
  11917. chain: document.getElementById('modal-rf-chain').value.trim(),
  11918. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11919. rule: document.getElementById('modal-rf-rule').value.trim(),
  11920. comment: document.getElementById('modal-rf-comment').value.trim(),
  11921. disabled: document.getElementById('modal-rf-disabled').checked
  11922. };
  11923. try {
  11924. const res = await fetch(`${API_BASE}/routing/filters`, {
  11925. method: 'POST',
  11926. headers: { 'Content-Type': 'application/json' },
  11927. body: JSON.stringify(payload)
  11928. });
  11929. if (res.ok) {
  11930. const data = await res.json();
  11931. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11932. showToast('Applied', 'Routing filter configuration applied', 'success');
  11933. loadDynamicRouting();
  11934. } else {
  11935. const err = await res.json();
  11936. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11937. }
  11938. } catch (err) {
  11939. showToast('Error', err.message, 'error');
  11940. }
  11941. }
  11942. async function moveRoutingFilterOrder(id, delta) {
  11943. const list = state.routingFilters || [];
  11944. const idx = list.findIndex(r => r.id === id);
  11945. if (idx < 0) return;
  11946. const targetIdx = idx + delta;
  11947. if (targetIdx < 0 || targetIdx >= list.length) return;
  11948. const currentOrder = list[idx].rule_order || 10;
  11949. const targetOrder = list[targetIdx].rule_order || 20;
  11950. list[idx].rule_order = targetOrder;
  11951. list[targetIdx].rule_order = currentOrder;
  11952. try {
  11953. await fetch(`${API_BASE}/routing/filters`, {
  11954. method: 'POST',
  11955. headers: { 'Content-Type': 'application/json' },
  11956. body: JSON.stringify(list[idx])
  11957. });
  11958. await fetch(`${API_BASE}/routing/filters`, {
  11959. method: 'POST',
  11960. headers: { 'Content-Type': 'application/json' },
  11961. body: JSON.stringify(list[targetIdx])
  11962. });
  11963. loadDynamicRouting();
  11964. } catch (e) {
  11965. console.error('Reorder error:', e);
  11966. }
  11967. }
  11968. async function deleteRoutingFilter(id) {
  11969. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11970. try {
  11971. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11972. if (res.ok) {
  11973. showToast('Deleted', 'Routing filter rule removed', 'info');
  11974. loadDynamicRouting();
  11975. } else {
  11976. const err = await res.json();
  11977. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11978. }
  11979. } catch (err) {
  11980. showToast('Error', err.message, 'error');
  11981. }
  11982. }
  11983. async function toggleRoutingFilterState(id, disabled) {
  11984. try {
  11985. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11986. method: 'POST',
  11987. headers: { 'Content-Type': 'application/json' },
  11988. body: JSON.stringify({ disabled })
  11989. });
  11990. if (res.ok) {
  11991. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11992. loadDynamicRouting();
  11993. } else {
  11994. const err = await res.json();
  11995. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11996. }
  11997. } catch (err) {
  11998. showToast('Error', err.message, 'error');
  11999. }
  12000. }
  12001. // -------------------------------------------------------------
  12002. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12003. // -------------------------------------------------------------
  12004. function openAddCommunityListModal() {
  12005. document.getElementById('modal-rf-cl-id').value = '';
  12006. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12007. document.getElementById('modal-rf-cl-name').value = '';
  12008. document.getElementById('modal-rf-cl-communities').value = '';
  12009. document.getElementById('modal-rf-cl-regexp').value = '';
  12010. document.getElementById('modal-rf-cl-comment').value = '';
  12011. document.getElementById('modal-rf-cl-disabled').checked = false;
  12012. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12013. }
  12014. function openEditCommunityListModal(id) {
  12015. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12016. if (!cl) return;
  12017. document.getElementById('modal-rf-cl-id').value = cl.id;
  12018. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12019. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12020. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12021. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12022. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12023. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12024. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12025. }
  12026. function closeCommunityListModal() {
  12027. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12028. }
  12029. async function submitCommunityList(e) {
  12030. e.preventDefault();
  12031. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12032. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12033. const payload = {
  12034. id: document.getElementById('modal-rf-cl-id').value,
  12035. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12036. communities: comms,
  12037. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12038. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12039. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12040. };
  12041. try {
  12042. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12043. method: 'POST',
  12044. headers: { 'Content-Type': 'application/json' },
  12045. body: JSON.stringify(payload)
  12046. });
  12047. if (res.ok) {
  12048. closeCommunityListModal();
  12049. showToast('Success', 'Community list saved', 'success');
  12050. loadDynamicRouting();
  12051. } else {
  12052. const err = await res.json();
  12053. showToast('Error', err.error || 'Failed to save community list', 'error');
  12054. }
  12055. } catch (err) {
  12056. showToast('Error', err.message, 'error');
  12057. }
  12058. }
  12059. async function deleteCommunityList(id) {
  12060. if (!confirm('Are you sure you want to delete this community list?')) return;
  12061. try {
  12062. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12063. if (res.ok) {
  12064. showToast('Deleted', 'Community list removed', 'info');
  12065. loadDynamicRouting();
  12066. } else {
  12067. const err = await res.json();
  12068. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12069. }
  12070. } catch (err) {
  12071. showToast('Error', err.message, 'error');
  12072. }
  12073. }
  12074. async function toggleCommunityListState(id, disabled) {
  12075. try {
  12076. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12077. method: 'POST',
  12078. headers: { 'Content-Type': 'application/json' },
  12079. body: JSON.stringify({ disabled })
  12080. });
  12081. if (res.ok) {
  12082. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12083. loadDynamicRouting();
  12084. } else {
  12085. const err = await res.json();
  12086. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12087. }
  12088. } catch (err) {
  12089. showToast('Error', err.message, 'error');
  12090. }
  12091. }
  12092. // -------------------------------------------------------------
  12093. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12094. // -------------------------------------------------------------
  12095. function openAddASListModal() {
  12096. document.getElementById('modal-rf-al-id').value = '';
  12097. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12098. document.getElementById('modal-rf-al-name').value = '';
  12099. document.getElementById('modal-rf-al-range').value = '';
  12100. document.getElementById('modal-rf-al-comment').value = '';
  12101. document.getElementById('modal-rf-al-disabled').checked = false;
  12102. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12103. }
  12104. function openEditASListModal(id) {
  12105. const al = (state.routingASLists || []).find(item => item.id === id);
  12106. if (!al) return;
  12107. document.getElementById('modal-rf-al-id').value = al.id;
  12108. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12109. document.getElementById('modal-rf-al-name').value = al.name || '';
  12110. document.getElementById('modal-rf-al-range').value = al.range || '';
  12111. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12112. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12113. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12114. }
  12115. function closeASListModal() {
  12116. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12117. }
  12118. async function submitASList(e) {
  12119. e.preventDefault();
  12120. const payload = {
  12121. id: document.getElementById('modal-rf-al-id').value,
  12122. name: document.getElementById('modal-rf-al-name').value.trim(),
  12123. range: document.getElementById('modal-rf-al-range').value.trim(),
  12124. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12125. disabled: document.getElementById('modal-rf-al-disabled').checked
  12126. };
  12127. try {
  12128. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12129. method: 'POST',
  12130. headers: { 'Content-Type': 'application/json' },
  12131. body: JSON.stringify(payload)
  12132. });
  12133. if (res.ok) {
  12134. closeASListModal();
  12135. showToast('Success', 'AS number list saved', 'success');
  12136. loadDynamicRouting();
  12137. } else {
  12138. const err = await res.json();
  12139. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12140. }
  12141. } catch (err) {
  12142. showToast('Error', err.message, 'error');
  12143. }
  12144. }
  12145. async function deleteASList(id) {
  12146. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12147. try {
  12148. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12149. if (res.ok) {
  12150. showToast('Deleted', 'AS list removed', 'info');
  12151. loadDynamicRouting();
  12152. } else {
  12153. const err = await res.json();
  12154. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12155. }
  12156. } catch (err) {
  12157. showToast('Error', err.message, 'error');
  12158. }
  12159. }
  12160. async function toggleASListState(id, disabled) {
  12161. try {
  12162. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12163. method: 'POST',
  12164. headers: { 'Content-Type': 'application/json' },
  12165. body: JSON.stringify({ disabled })
  12166. });
  12167. if (res.ok) {
  12168. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12169. loadDynamicRouting();
  12170. } else {
  12171. const err = await res.json();
  12172. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12173. }
  12174. } catch (err) {
  12175. showToast('Error', err.message, 'error');
  12176. }
  12177. }
  12178. // ==========================================
  12179. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12180. // ==========================================
  12181. function loadToolsView() {
  12182. populateToolsInterfaces();
  12183. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12184. }
  12185. function populateToolsInterfaces() {
  12186. const pingSel = document.getElementById('tools-ping-iface');
  12187. const traceSel = document.getElementById('tools-tr-iface');
  12188. let opts = '<option value="">Auto (Default Route)</option>';
  12189. if (Array.isArray(state.interfaces)) {
  12190. state.interfaces.forEach(iface => {
  12191. if (iface.name) {
  12192. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12193. }
  12194. });
  12195. }
  12196. if (pingSel) {
  12197. const cur = pingSel.value;
  12198. pingSel.innerHTML = opts;
  12199. if (cur) pingSel.value = cur;
  12200. }
  12201. if (traceSel) {
  12202. const cur = traceSel.value;
  12203. traceSel.innerHTML = opts;
  12204. if (cur) traceSel.value = cur;
  12205. }
  12206. }
  12207. function switchToolsSubTab(subTab) {
  12208. state.activeToolsSubTab = subTab;
  12209. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12210. tabs.forEach(t => {
  12211. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12212. const view = document.getElementById(`tools-view-${t}`);
  12213. if (btn) {
  12214. if (t === subTab) {
  12215. 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';
  12216. } else {
  12217. 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';
  12218. }
  12219. }
  12220. if (view) {
  12221. if (t === subTab) {
  12222. view.classList.remove('hidden');
  12223. } else {
  12224. view.classList.add('hidden');
  12225. }
  12226. }
  12227. });
  12228. }
  12229. function setPortPreset(port) {
  12230. const input = document.getElementById('tools-port-num');
  12231. if (input) input.value = port;
  12232. }
  12233. let pingAbortController = null;
  12234. let tracerouteAbortController = null;
  12235. function clearPingTable() {
  12236. const tbody = document.getElementById('tools-ping-tbody');
  12237. if (tbody) tbody.innerHTML = '';
  12238. const rawEl = document.getElementById('tools-ping-raw');
  12239. if (rawEl) rawEl.innerText = '';
  12240. const sentEl = document.getElementById('tools-ping-stat-sent');
  12241. if (sentEl) sentEl.innerText = '0';
  12242. const recvEl = document.getElementById('tools-ping-stat-recv');
  12243. if (recvEl) recvEl.innerText = '0';
  12244. const lossEl = document.getElementById('tools-ping-stat-loss');
  12245. if (lossEl) lossEl.innerText = '0%';
  12246. const avgEl = document.getElementById('tools-ping-stat-avg');
  12247. if (avgEl) avgEl.innerText = '0 ms';
  12248. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12249. if (minMaxEl) minMaxEl.innerText = '-';
  12250. const badge = document.getElementById('tools-ping-status-badge');
  12251. if (badge) {
  12252. badge.className = '';
  12253. badge.innerText = '';
  12254. }
  12255. }
  12256. function clearTracerouteTable() {
  12257. const tbody = document.getElementById('tools-tr-tbody');
  12258. if (tbody) tbody.innerHTML = '';
  12259. const rawEl = document.getElementById('tools-tr-raw');
  12260. if (rawEl) rawEl.innerText = '';
  12261. const statHops = document.getElementById('tools-tr-hops-count');
  12262. if (statHops) statHops.innerText = '0 Hops';
  12263. }
  12264. function resetPingButton() {
  12265. const btn = document.getElementById('tools-ping-btn');
  12266. const btnText = document.getElementById('tools-ping-btn-text');
  12267. const spinner = document.getElementById('tools-ping-spinner');
  12268. if (btn) {
  12269. btn.disabled = false;
  12270. 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';
  12271. }
  12272. if (btnText) btnText.innerText = 'Start Ping';
  12273. if (spinner) spinner.classList.add('hidden');
  12274. }
  12275. function setPingRunningButton() {
  12276. const btn = document.getElementById('tools-ping-btn');
  12277. const btnText = document.getElementById('tools-ping-btn-text');
  12278. const spinner = document.getElementById('tools-ping-spinner');
  12279. if (btn) {
  12280. btn.disabled = false;
  12281. 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';
  12282. }
  12283. if (btnText) btnText.innerText = 'Stop Ping';
  12284. if (spinner) spinner.classList.remove('hidden');
  12285. }
  12286. function resetTracerouteButton() {
  12287. const btn = document.getElementById('tools-tr-btn');
  12288. const btnText = document.getElementById('tools-tr-btn-text');
  12289. const spinner = document.getElementById('tools-tr-spinner');
  12290. if (btn) {
  12291. btn.disabled = false;
  12292. 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';
  12293. }
  12294. if (btnText) btnText.innerText = 'Start Traceroute';
  12295. if (spinner) spinner.classList.add('hidden');
  12296. }
  12297. function setTracerouteRunningButton() {
  12298. const btn = document.getElementById('tools-tr-btn');
  12299. const btnText = document.getElementById('tools-tr-btn-text');
  12300. const spinner = document.getElementById('tools-tr-spinner');
  12301. if (btn) {
  12302. btn.disabled = false;
  12303. 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';
  12304. }
  12305. if (btnText) btnText.innerText = 'Stop Traceroute';
  12306. if (spinner) spinner.classList.remove('hidden');
  12307. }
  12308. async function executePing(e) {
  12309. if (e) e.preventDefault();
  12310. // If already running, clicking the button stops the stream!
  12311. if (pingAbortController) {
  12312. pingAbortController.abort();
  12313. pingAbortController = null;
  12314. resetPingButton();
  12315. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12316. return;
  12317. }
  12318. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12319. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12320. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12321. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12322. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12323. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12324. if (!target) {
  12325. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12326. return;
  12327. }
  12328. clearPingTable();
  12329. const resCard = document.getElementById('tools-ping-results');
  12330. if (resCard) resCard.classList.remove('hidden');
  12331. pingAbortController = new AbortController();
  12332. setPingRunningButton();
  12333. try {
  12334. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12335. method: 'POST',
  12336. headers: { 'Content-Type': 'application/json' },
  12337. body: JSON.stringify({
  12338. target,
  12339. count,
  12340. size,
  12341. timeout,
  12342. interface: iface,
  12343. dont_frag: dontFrag
  12344. }),
  12345. signal: pingAbortController.signal
  12346. });
  12347. if (!res.ok) {
  12348. const errText = await res.text();
  12349. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12350. resetPingButton();
  12351. pingAbortController = null;
  12352. return;
  12353. }
  12354. const reader = res.body.getReader();
  12355. const decoder = new TextDecoder('utf-8');
  12356. let buffer = '';
  12357. while (true) {
  12358. const { done, value } = await reader.read();
  12359. if (done) break;
  12360. buffer += decoder.decode(value, { stream: true });
  12361. const blocks = buffer.split('\n\n');
  12362. buffer = blocks.pop() || '';
  12363. for (const block of blocks) {
  12364. const trimmed = block.trim();
  12365. if (!trimmed) continue;
  12366. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12367. try {
  12368. const evt = JSON.parse(line);
  12369. handleLivePingEvent(evt);
  12370. } catch (parseErr) {
  12371. console.warn('Ping SSE parse error:', parseErr, line);
  12372. }
  12373. }
  12374. }
  12375. } catch (err) {
  12376. if (err.name === 'AbortError') {
  12377. // User aborted normally
  12378. } else {
  12379. showToast('Ping Error', err.message, 'error');
  12380. }
  12381. } finally {
  12382. pingAbortController = null;
  12383. resetPingButton();
  12384. }
  12385. }
  12386. function handleLivePingEvent(evt) {
  12387. const sentEl = document.getElementById('tools-ping-stat-sent');
  12388. const recvEl = document.getElementById('tools-ping-stat-recv');
  12389. const lossEl = document.getElementById('tools-ping-stat-loss');
  12390. const avgEl = document.getElementById('tools-ping-stat-avg');
  12391. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12392. const badge = document.getElementById('tools-ping-status-badge');
  12393. const tbody = document.getElementById('tools-ping-tbody');
  12394. const rawEl = document.getElementById('tools-ping-raw');
  12395. if (evt.raw && rawEl) {
  12396. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12397. rawEl.scrollTop = rawEl.scrollHeight;
  12398. }
  12399. if (evt.type === 'reply') {
  12400. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12401. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12402. if (lossEl && evt.packet_loss_pct !== undefined) {
  12403. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12404. lossEl.className = evt.packet_loss_pct === 0
  12405. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12406. : (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');
  12407. }
  12408. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12409. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12410. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12411. }
  12412. if (badge) {
  12413. if (evt.packet_loss_pct === 0) {
  12414. 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';
  12415. badge.innerText = '100% OK';
  12416. } else {
  12417. 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';
  12418. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12419. }
  12420. }
  12421. if (tbody) {
  12422. const tr = document.createElement('tr');
  12423. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12424. tr.innerHTML = `
  12425. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12426. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12427. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12428. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12429. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12430. <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>
  12431. `;
  12432. tbody.appendChild(tr);
  12433. }
  12434. } else if (evt.type === 'timeout') {
  12435. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12436. if (lossEl && evt.packet_loss_pct !== undefined) {
  12437. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12438. 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';
  12439. }
  12440. if (badge) {
  12441. 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';
  12442. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12443. }
  12444. if (tbody) {
  12445. const tr = document.createElement('tr');
  12446. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12447. tr.innerHTML = `
  12448. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12449. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12450. <td class="py-2 px-3 text-slate-600">--</td>
  12451. <td class="py-2 px-3 text-slate-600">--</td>
  12452. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12453. <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>
  12454. `;
  12455. tbody.appendChild(tr);
  12456. }
  12457. } else if (evt.type === 'unreach') {
  12458. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12459. if (lossEl && evt.packet_loss_pct !== undefined) {
  12460. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12461. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12462. }
  12463. if (badge) {
  12464. 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';
  12465. badge.innerText = 'UNREACHABLE';
  12466. }
  12467. if (tbody) {
  12468. const tr = document.createElement('tr');
  12469. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12470. tr.innerHTML = `
  12471. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12472. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12473. <td class="py-2 px-3 text-slate-600">--</td>
  12474. <td class="py-2 px-3 text-slate-600">--</td>
  12475. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12476. <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>
  12477. `;
  12478. tbody.appendChild(tr);
  12479. }
  12480. } else if (evt.type === 'stats') {
  12481. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12482. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12483. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12484. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12485. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12486. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12487. }
  12488. } else if (evt.type === 'done') {
  12489. 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');
  12490. }
  12491. }
  12492. async function executeTraceroute(e) {
  12493. if (e) e.preventDefault();
  12494. if (tracerouteAbortController) {
  12495. tracerouteAbortController.abort();
  12496. tracerouteAbortController = null;
  12497. resetTracerouteButton();
  12498. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12499. return;
  12500. }
  12501. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12502. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12503. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12504. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12505. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12506. if (!target) {
  12507. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12508. return;
  12509. }
  12510. clearTracerouteTable();
  12511. const resCard = document.getElementById('tools-tr-results');
  12512. if (resCard) resCard.classList.remove('hidden');
  12513. tracerouteAbortController = new AbortController();
  12514. setTracerouteRunningButton();
  12515. try {
  12516. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12517. method: 'POST',
  12518. headers: { 'Content-Type': 'application/json' },
  12519. body: JSON.stringify({
  12520. target,
  12521. max_hops: maxHops,
  12522. protocol,
  12523. interface: iface,
  12524. resolve
  12525. }),
  12526. signal: tracerouteAbortController.signal
  12527. });
  12528. if (!res.ok) {
  12529. const errText = await res.text();
  12530. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12531. resetTracerouteButton();
  12532. tracerouteAbortController = null;
  12533. return;
  12534. }
  12535. const reader = res.body.getReader();
  12536. const decoder = new TextDecoder('utf-8');
  12537. let buffer = '';
  12538. while (true) {
  12539. const { done, value } = await reader.read();
  12540. if (done) break;
  12541. buffer += decoder.decode(value, { stream: true });
  12542. const blocks = buffer.split('\n\n');
  12543. buffer = blocks.pop() || '';
  12544. for (const block of blocks) {
  12545. const trimmed = block.trim();
  12546. if (!trimmed) continue;
  12547. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12548. try {
  12549. const evt = JSON.parse(line);
  12550. handleLiveTracerouteEvent(evt);
  12551. } catch (parseErr) {
  12552. console.warn('Traceroute SSE parse error:', parseErr, line);
  12553. }
  12554. }
  12555. }
  12556. } catch (err) {
  12557. if (err.name === 'AbortError') {
  12558. // User aborted normally
  12559. } else {
  12560. showToast('Traceroute Error', err.message, 'error');
  12561. }
  12562. } finally {
  12563. tracerouteAbortController = null;
  12564. resetTracerouteButton();
  12565. }
  12566. }
  12567. function handleLiveTracerouteEvent(evt) {
  12568. const statHops = document.getElementById('tools-tr-hops-count');
  12569. const tbody = document.getElementById('tools-tr-tbody');
  12570. const rawEl = document.getElementById('tools-tr-raw');
  12571. if (evt.raw && rawEl) {
  12572. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12573. rawEl.scrollTop = rawEl.scrollHeight;
  12574. }
  12575. if (evt.hops_count !== undefined && statHops) {
  12576. statHops.innerText = `${evt.hops_count} Hops`;
  12577. }
  12578. if (evt.type === 'hop' && evt.hop && tbody) {
  12579. const h = evt.hop;
  12580. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12581. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12582. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12583. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12584. const tr = document.createElement('tr');
  12585. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12586. tr.innerHTML = `
  12587. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12588. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12589. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12590. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12591. <td class="py-2.5 px-3 text-right">
  12592. ${isTimeout
  12593. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12594. : '<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>'}
  12595. </td>
  12596. `;
  12597. tbody.appendChild(tr);
  12598. } else if (evt.type === 'done') {
  12599. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12600. }
  12601. }
  12602. async function executeMTR(e) {
  12603. if (e) e.preventDefault();
  12604. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12605. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12606. if (!target) {
  12607. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12608. return;
  12609. }
  12610. const btn = document.getElementById('tools-mtr-btn');
  12611. const spinner = document.getElementById('tools-mtr-spinner');
  12612. if (btn) btn.disabled = true;
  12613. if (spinner) spinner.classList.remove('hidden');
  12614. try {
  12615. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12616. method: 'POST',
  12617. headers: { 'Content-Type': 'application/json' },
  12618. body: JSON.stringify({ target, count: cycles })
  12619. });
  12620. const data = await res.json();
  12621. if (!res.ok) {
  12622. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12623. return;
  12624. }
  12625. const resCard = document.getElementById('tools-mtr-results');
  12626. if (resCard) resCard.classList.remove('hidden');
  12627. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12628. const statHops = document.getElementById('tools-mtr-hops-count');
  12629. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12630. const tbody = document.getElementById('tools-mtr-tbody');
  12631. if (tbody) {
  12632. if (hopsCount > 0) {
  12633. tbody.innerHTML = data.hops.map(h => {
  12634. 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');
  12635. return `
  12636. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12637. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12638. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12639. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12640. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12641. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12642. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12643. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12644. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12645. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12646. </tr>
  12647. `;
  12648. }).join('');
  12649. } else {
  12650. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12651. }
  12652. }
  12653. const rawEl = document.getElementById('tools-mtr-raw');
  12654. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12655. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12656. } catch (err) {
  12657. showToast('MTR Error', err.message, 'error');
  12658. } finally {
  12659. if (btn) btn.disabled = false;
  12660. if (spinner) spinner.classList.add('hidden');
  12661. }
  12662. }
  12663. async function executeDNS(e) {
  12664. if (e) e.preventDefault();
  12665. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12666. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12667. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12668. if (!domain) {
  12669. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12670. return;
  12671. }
  12672. const btn = document.getElementById('tools-dns-btn');
  12673. const spinner = document.getElementById('tools-dns-spinner');
  12674. if (btn) btn.disabled = true;
  12675. if (spinner) spinner.classList.remove('hidden');
  12676. try {
  12677. const res = await fetch(`${API_BASE}/tools/dns`, {
  12678. method: 'POST',
  12679. headers: { 'Content-Type': 'application/json' },
  12680. body: JSON.stringify({ domain, type, server })
  12681. });
  12682. const data = await res.json();
  12683. if (!res.ok) {
  12684. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12685. return;
  12686. }
  12687. const resCard = document.getElementById('tools-dns-results');
  12688. if (resCard) resCard.classList.remove('hidden');
  12689. const metaEl = document.getElementById('tools-dns-meta');
  12690. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12691. const tbody = document.getElementById('tools-dns-tbody');
  12692. if (tbody) {
  12693. if (Array.isArray(data.records) && data.records.length > 0) {
  12694. tbody.innerHTML = data.records.map(r => `
  12695. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12696. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12697. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12698. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12699. <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>
  12700. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12701. </tr>
  12702. `).join('');
  12703. } else {
  12704. 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>`;
  12705. }
  12706. }
  12707. const rawEl = document.getElementById('tools-dns-raw');
  12708. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12709. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12710. } catch (err) {
  12711. showToast('DNS Error', err.message, 'error');
  12712. } finally {
  12713. if (btn) btn.disabled = false;
  12714. if (spinner) spinner.classList.add('hidden');
  12715. }
  12716. }
  12717. async function executePortProbe(e) {
  12718. if (e) e.preventDefault();
  12719. const target = document.getElementById('tools-port-target')?.value?.trim();
  12720. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12721. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12722. if (!target || !port) {
  12723. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12724. return;
  12725. }
  12726. const btn = document.getElementById('tools-port-btn');
  12727. const spinner = document.getElementById('tools-port-spinner');
  12728. if (btn) btn.disabled = true;
  12729. if (spinner) spinner.classList.remove('hidden');
  12730. try {
  12731. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12732. method: 'POST',
  12733. headers: { 'Content-Type': 'application/json' },
  12734. body: JSON.stringify({ target, port, timeout })
  12735. });
  12736. const data = await res.json();
  12737. if (!res.ok) {
  12738. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12739. return;
  12740. }
  12741. const resCard = document.getElementById('tools-port-results');
  12742. if (resCard) resCard.classList.remove('hidden');
  12743. const banner = document.getElementById('tools-port-banner');
  12744. const icon = document.getElementById('tools-port-icon');
  12745. const title = document.getElementById('tools-port-title');
  12746. const sub = document.getElementById('tools-port-sub');
  12747. const latency = document.getElementById('tools-port-latency');
  12748. if (data.open) {
  12749. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12750. if (icon) {
  12751. 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';
  12752. icon.innerText = '✓';
  12753. }
  12754. if (title) {
  12755. title.className = 'text-sm font-bold text-emerald-300';
  12756. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12757. }
  12758. if (sub) {
  12759. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12760. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12761. }
  12762. if (latency) {
  12763. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12764. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12765. }
  12766. } else {
  12767. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12768. if (icon) {
  12769. 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';
  12770. icon.innerText = '✕';
  12771. }
  12772. if (title) {
  12773. title.className = 'text-sm font-bold text-rose-300';
  12774. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12775. }
  12776. if (sub) {
  12777. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12778. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12779. }
  12780. if (latency) {
  12781. latency.className = 'text-base font-bold font-mono text-slate-500';
  12782. latency.innerText = '--';
  12783. }
  12784. }
  12785. const rawEl = document.getElementById('tools-port-raw');
  12786. 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'}`);
  12787. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12788. } catch (err) {
  12789. showToast('Probe Error', err.message, 'error');
  12790. } finally {
  12791. if (btn) btn.disabled = false;
  12792. if (spinner) spinner.classList.add('hidden');
  12793. }
  12794. }
  12795. // ==========================================
  12796. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12797. // ==========================================
  12798. async function loadDHCPClients(showToastMsg = false) {
  12799. try {
  12800. const [clientsRes, sumRes] = await Promise.all([
  12801. fetch(`${API_BASE}/dhcp/clients`),
  12802. fetch(`${API_BASE}/dhcp/clients/summary`)
  12803. ]);
  12804. if (clientsRes.ok) {
  12805. state.dhcpClients = await clientsRes.json();
  12806. }
  12807. if (sumRes.ok) {
  12808. state.dhcpSummary = await sumRes.json();
  12809. }
  12810. renderDHCPClients();
  12811. updateDHCPSummaryCards();
  12812. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12813. if (bDhcp && state.dhcpSummary) {
  12814. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12815. }
  12816. if (showToastMsg) {
  12817. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12818. }
  12819. } catch (err) {
  12820. console.error('Failed to load DHCP clients:', err);
  12821. if (showToastMsg) {
  12822. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12823. }
  12824. }
  12825. }
  12826. function updateDHCPSummaryCards() {
  12827. const sum = state.dhcpSummary || {
  12828. total_clients: (state.dhcpClients || []).length,
  12829. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12830. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12831. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12832. };
  12833. const totalEl = document.getElementById('dhcp-stat-total');
  12834. const boundEl = document.getElementById('dhcp-stat-bound');
  12835. const searchEl = document.getElementById('dhcp-stat-searching');
  12836. const disEl = document.getElementById('dhcp-stat-disabled');
  12837. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12838. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12839. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12840. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12841. }
  12842. function renderDHCPClients() {
  12843. const tbody = document.getElementById('dhcp-clients-tbody');
  12844. const emptyState = document.getElementById('dhcp-clients-empty');
  12845. if (!tbody) return;
  12846. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12847. if (clients.length === 0) {
  12848. tbody.innerHTML = '';
  12849. if (emptyState) emptyState.classList.remove('hidden');
  12850. return;
  12851. }
  12852. if (emptyState) emptyState.classList.add('hidden');
  12853. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12854. if (tbody.dataset.sig === sig) return;
  12855. tbody.dataset.sig = sig;
  12856. tbody.innerHTML = clients.map(c => {
  12857. let statusBadge = '';
  12858. if (!c.enabled) {
  12859. 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>';
  12860. } else if (c.status === 'bound') {
  12861. 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>';
  12862. } else if (c.status === 'searching') {
  12863. 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>';
  12864. } else if (c.status === 'stopped') {
  12865. 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>';
  12866. } else {
  12867. 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>`;
  12868. }
  12869. 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>';
  12870. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12871. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12872. 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>';
  12873. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12874. // Option flags
  12875. const flags = [];
  12876. 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>');
  12877. 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>');
  12878. 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>');
  12879. 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>`);
  12880. return `
  12881. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12882. <td class="py-3 px-4">
  12883. <div class="flex items-center gap-2">
  12884. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12885. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12886. </div>
  12887. </td>
  12888. <td class="py-3 px-4">${statusBadge}</td>
  12889. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12890. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12891. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12892. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12893. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12894. <td class="py-3 px-4">
  12895. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12896. </td>
  12897. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12898. ${c.enabled ? `
  12899. <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>
  12900. <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>
  12901. <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>
  12902. ` : `
  12903. <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>
  12904. `}
  12905. <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>
  12906. <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>
  12907. </td>
  12908. </tr>
  12909. `;
  12910. }).join('');
  12911. }
  12912. function openDHCPClientModal(clientId = null) {
  12913. const modal = document.getElementById('modal-dhcp-client');
  12914. if (!modal) return;
  12915. const title = document.getElementById('modal-dhcp-title');
  12916. const idInput = document.getElementById('modal-dhcp-id');
  12917. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12918. const distInput = document.getElementById('modal-dhcp-distance');
  12919. const commentInput = document.getElementById('modal-dhcp-comment');
  12920. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12921. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12922. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12923. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12924. // Populate interfaces
  12925. if (ifaceSelect) {
  12926. let opts = '<option value="">Select interface...</option>';
  12927. const allIfaces = state.interfaces || [];
  12928. const allVlans = state.vlans || [];
  12929. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12930. // Group 1: Physical & Bridge Interfaces
  12931. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12932. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12933. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12934. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12935. });
  12936. opts += '</optgroup>';
  12937. // Group 2: VLAN Interfaces
  12938. if (allVlans.length > 0) {
  12939. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12940. allVlans.forEach(v => {
  12941. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12942. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12943. });
  12944. opts += '</optgroup>';
  12945. }
  12946. ifaceSelect.innerHTML = opts;
  12947. }
  12948. if (clientId) {
  12949. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12950. if (client) {
  12951. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12952. if (idInput) idInput.value = client.id;
  12953. if (ifaceSelect) {
  12954. ifaceSelect.value = client.interface;
  12955. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12956. }
  12957. if (distInput) distInput.value = client.default_route_distance || 1;
  12958. if (commentInput) commentInput.value = client.comment || '';
  12959. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12960. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12961. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12962. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12963. }
  12964. } else {
  12965. if (title) title.innerText = 'Add DHCP Client';
  12966. if (idInput) idInput.value = '';
  12967. if (ifaceSelect) {
  12968. ifaceSelect.value = '';
  12969. ifaceSelect.disabled = false;
  12970. }
  12971. if (distInput) distInput.value = 1;
  12972. if (commentInput) commentInput.value = '';
  12973. if (defRouteCheck) defRouteCheck.checked = true;
  12974. if (peerDnsCheck) peerDnsCheck.checked = true;
  12975. if (peerNtpCheck) peerNtpCheck.checked = true;
  12976. if (enabledCheck) enabledCheck.checked = true;
  12977. }
  12978. modal.classList.remove('hidden');
  12979. }
  12980. function openDHCPClientModalForIface(ifaceName) {
  12981. openDHCPClientModal();
  12982. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12983. if (ifaceSelect && ifaceName) {
  12984. ifaceSelect.value = ifaceName;
  12985. }
  12986. }
  12987. function closeDHCPClientModal() {
  12988. const modal = document.getElementById('modal-dhcp-client');
  12989. if (modal) modal.classList.add('hidden');
  12990. }
  12991. async function submitSaveDHCPClient(e) {
  12992. if (e) e.preventDefault();
  12993. const id = document.getElementById('modal-dhcp-id')?.value;
  12994. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12995. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12996. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12997. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12998. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12999. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13000. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13001. if (!id && !iface) {
  13002. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13003. return;
  13004. }
  13005. try {
  13006. let res;
  13007. if (id) {
  13008. // PUT update
  13009. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13010. method: 'PUT',
  13011. headers: { 'Content-Type': 'application/json' },
  13012. body: JSON.stringify({
  13013. enabled,
  13014. add_default_route: defRoute,
  13015. default_route_distance: distance,
  13016. use_peer_dns: peerDns,
  13017. use_peer_ntp: peerNtp,
  13018. comment
  13019. })
  13020. });
  13021. } else {
  13022. // POST create
  13023. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13024. method: 'POST',
  13025. headers: { 'Content-Type': 'application/json' },
  13026. body: JSON.stringify({
  13027. interface: iface,
  13028. enabled,
  13029. add_default_route: defRoute,
  13030. default_route_distance: distance,
  13031. use_peer_dns: peerDns,
  13032. use_peer_ntp: peerNtp,
  13033. comment
  13034. })
  13035. });
  13036. }
  13037. const data = await res.json();
  13038. if (!res.ok) {
  13039. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13040. return;
  13041. }
  13042. closeDHCPClientModal();
  13043. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13044. await loadDHCPClients();
  13045. fetchData(); // refresh interfaces list with new lease/status
  13046. } catch (err) {
  13047. showToast('Error', err.message, 'error');
  13048. }
  13049. }
  13050. async function toggleDHCPClientState(id, enabled) {
  13051. try {
  13052. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13053. method: 'POST',
  13054. headers: { 'Content-Type': 'application/json' },
  13055. body: JSON.stringify({ enabled })
  13056. });
  13057. const data = await res.json();
  13058. if (!res.ok) {
  13059. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13060. return;
  13061. }
  13062. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13063. await loadDHCPClients();
  13064. fetchData();
  13065. } catch (err) {
  13066. showToast('Error', err.message, 'error');
  13067. }
  13068. }
  13069. async function renewDHCPClient(id) {
  13070. try {
  13071. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13072. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13073. method: 'POST'
  13074. });
  13075. const data = await res.json();
  13076. if (!res.ok) {
  13077. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13078. return;
  13079. }
  13080. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13081. setTimeout(() => {
  13082. loadDHCPClients();
  13083. fetchData();
  13084. }, 1500);
  13085. } catch (err) {
  13086. showToast('Error', err.message, 'error');
  13087. }
  13088. }
  13089. async function releaseDHCPClient(id) {
  13090. try {
  13091. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13092. method: 'POST'
  13093. });
  13094. const data = await res.json();
  13095. if (!res.ok) {
  13096. showToast('Error', data.error || 'Failed to release lease', 'error');
  13097. return;
  13098. }
  13099. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13100. await loadDHCPClients();
  13101. fetchData();
  13102. } catch (err) {
  13103. showToast('Error', err.message, 'error');
  13104. }
  13105. }
  13106. async function deleteDHCPClient(id, ifaceName) {
  13107. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13108. return;
  13109. }
  13110. try {
  13111. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13112. method: 'DELETE'
  13113. });
  13114. const data = await res.json();
  13115. if (!res.ok) {
  13116. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13117. return;
  13118. }
  13119. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13120. await loadDHCPClients();
  13121. fetchData();
  13122. } catch (err) {
  13123. showToast('Error', err.message, 'error');
  13124. }
  13125. }
  13126. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13127. async function loadDHCPServer(populate = true) {
  13128. try {
  13129. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13130. fetch(`${API_BASE}/dhcp-server/summary`),
  13131. fetch(`${API_BASE}/dhcp-server/servers`),
  13132. fetch(`${API_BASE}/dhcp-server/networks`),
  13133. fetch(`${API_BASE}/dhcp-server/leases`),
  13134. fetch(`${API_BASE}/dhcp-server/options`)
  13135. ]);
  13136. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13137. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13138. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13139. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13140. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13141. const sum = state.dhcpServerSummary || {};
  13142. const srvs = state.dhcpServers || [];
  13143. const nets = state.dhcpNetworks || [];
  13144. const leases = state.dhcpLeases || [];
  13145. const opts = state.dhcpOptions || [];
  13146. // KPI Cards
  13147. const statActive = document.getElementById('dhcp-server-stat-active');
  13148. if (statActive) {
  13149. const activeCount = srvs.filter(s => s.running).length;
  13150. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13151. }
  13152. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13153. if (statLeases) {
  13154. statLeases.innerText = leases.length;
  13155. }
  13156. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13157. if (statLeasesSub) {
  13158. const dyn = leases.filter(l => l.dynamic).length;
  13159. const st = leases.filter(l => !l.dynamic).length;
  13160. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13161. }
  13162. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13163. if (statNetworks) {
  13164. statNetworks.innerText = nets.length;
  13165. }
  13166. // Subtab Badges
  13167. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13168. if (bSrv) bSrv.innerText = srvs.length;
  13169. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13170. if (bNet) bNet.innerText = nets.length;
  13171. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13172. if (bLease) bLease.innerText = leases.length;
  13173. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13174. if (bOpt) bOpt.innerText = opts.length;
  13175. // Sidebar Badge
  13176. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13177. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13178. renderCurrentDHCPServerTab();
  13179. } catch (err) {
  13180. console.error('Failed to load DHCP Server:', err);
  13181. }
  13182. }
  13183. function switchDHCPServerTab(tab) {
  13184. state.dhcpServerTab = tab;
  13185. const tabs = ['servers', 'networks', 'leases', 'options'];
  13186. tabs.forEach(t => {
  13187. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13188. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13189. if (panel) {
  13190. if (t === tab) panel.classList.remove('hidden');
  13191. else panel.classList.add('hidden');
  13192. }
  13193. if (btn) {
  13194. if (t === tab) {
  13195. 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';
  13196. } else {
  13197. 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';
  13198. }
  13199. }
  13200. });
  13201. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13202. if (addBtn) {
  13203. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13204. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13205. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13206. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13207. }
  13208. renderCurrentDHCPServerTab();
  13209. }
  13210. function handleDHCPServerPrimaryAdd() {
  13211. const tab = state.dhcpServerTab || 'servers';
  13212. if (tab === 'servers') openAddDHCPServerModal();
  13213. else if (tab === 'networks') openAddDHCPNetworkModal();
  13214. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13215. else if (tab === 'options') openAddDHCPOptionModal();
  13216. }
  13217. function renderCurrentDHCPServerTab() {
  13218. const tab = state.dhcpServerTab || 'servers';
  13219. if (tab === 'servers') renderDHCPServers();
  13220. else if (tab === 'networks') renderDHCPNetworks();
  13221. else if (tab === 'leases') renderDHCPLeases();
  13222. else if (tab === 'options') renderDHCPOptions();
  13223. }
  13224. function renderDHCPServers() {
  13225. const tbody = document.getElementById('dhcp-server-tbody');
  13226. const empty = document.getElementById('dhcp-server-empty');
  13227. if (!tbody) return;
  13228. const servers = state.dhcpServers || [];
  13229. if (servers.length === 0) {
  13230. tbody.innerHTML = '';
  13231. empty?.classList.remove('hidden');
  13232. return;
  13233. }
  13234. empty?.classList.add('hidden');
  13235. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13236. if (tbody.dataset.sig === sig) return;
  13237. tbody.dataset.sig = sig;
  13238. tbody.innerHTML = '';
  13239. servers.forEach(s => {
  13240. const tr = document.createElement('tr');
  13241. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13242. tr.innerHTML = `
  13243. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13244. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13245. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13246. <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>
  13247. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13248. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13249. <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>
  13250. <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>
  13251. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13252. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13253. <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>
  13254. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13255. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13256. </td>
  13257. `;
  13258. tbody.appendChild(tr);
  13259. });
  13260. }
  13261. function renderDHCPNetworks() {
  13262. const tbody = document.getElementById('dhcp-networks-tbody');
  13263. const empty = document.getElementById('dhcp-networks-empty');
  13264. if (!tbody) return;
  13265. tbody.innerHTML = '';
  13266. const networks = state.dhcpNetworks || [];
  13267. if (networks.length === 0) {
  13268. empty?.classList.remove('hidden');
  13269. return;
  13270. }
  13271. empty?.classList.add('hidden');
  13272. networks.forEach(n => {
  13273. const tr = document.createElement('tr');
  13274. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13275. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13276. const optionsChips = (n.dhcp_options || []).map(optId => {
  13277. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13278. if (!opt) return '';
  13279. 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>`;
  13280. }).filter(Boolean).join('');
  13281. tr.innerHTML = `
  13282. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13283. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13284. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13285. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13286. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13287. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13288. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13289. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13290. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13291. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13292. </td>
  13293. `;
  13294. tbody.appendChild(tr);
  13295. });
  13296. }
  13297. function renderDHCPLeases() {
  13298. const tbody = document.getElementById('dhcp-leases-tbody');
  13299. const empty = document.getElementById('dhcp-leases-empty');
  13300. if (!tbody) return;
  13301. tbody.innerHTML = '';
  13302. const leases = state.dhcpLeases || [];
  13303. if (leases.length === 0) {
  13304. empty?.classList.remove('hidden');
  13305. return;
  13306. }
  13307. empty?.classList.add('hidden');
  13308. leases.forEach(l => {
  13309. const tr = document.createElement('tr');
  13310. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13311. 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>';
  13312. const statusBadge = l.status === 'bound'
  13313. ? '<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>'
  13314. : l.status === 'static'
  13315. ? '<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>'
  13316. : '<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>';
  13317. const makeStaticBtn = l.dynamic
  13318. ? `<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>`
  13319. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13320. tr.innerHTML = `
  13321. <td class="py-2.5 px-3 text-center">${flag}</td>
  13322. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13323. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13324. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13325. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13326. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13327. <td class="py-2.5 px-3">${statusBadge}</td>
  13328. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13329. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13330. ${makeStaticBtn}
  13331. </td>
  13332. `;
  13333. tbody.appendChild(tr);
  13334. });
  13335. }
  13336. function renderDHCPOptions() {
  13337. const tbody = document.getElementById('dhcp-options-tbody');
  13338. const empty = document.getElementById('dhcp-options-empty');
  13339. if (!tbody) return;
  13340. tbody.innerHTML = '';
  13341. const options = state.dhcpOptions || [];
  13342. if (options.length === 0) {
  13343. empty?.classList.remove('hidden');
  13344. return;
  13345. }
  13346. empty?.classList.add('hidden');
  13347. options.forEach(o => {
  13348. const tr = document.createElement('tr');
  13349. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13350. tr.innerHTML = `
  13351. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13352. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13353. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13354. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13355. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13356. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13357. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13358. </td>
  13359. `;
  13360. tbody.appendChild(tr);
  13361. });
  13362. }
  13363. // ==================== MODALS & ACTIONS: SERVER ====================
  13364. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13365. const sel = document.getElementById(elemId);
  13366. if (!sel) return;
  13367. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13368. const networks = state.dhcpNetworks || [];
  13369. networks.forEach(n => {
  13370. const opt = document.createElement('option');
  13371. opt.value = n.address;
  13372. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13373. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13374. opt.selected = true;
  13375. }
  13376. sel.appendChild(opt);
  13377. });
  13378. }
  13379. function onDHCPServerNetworkChange() {
  13380. const netSel = document.getElementById('dhcp-server-modal-network');
  13381. if (!netSel) return;
  13382. const netVal = netSel.value;
  13383. if (!netVal) return;
  13384. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13385. if (!poolInput) return;
  13386. // Auto-calculate suggested address pool based on subnet CIDR
  13387. const parts = netVal.split('/');
  13388. const ip = parts[0];
  13389. const cidr = parseInt(parts[1] || '24', 10);
  13390. if (cidr === 24) {
  13391. const octets = ip.split('.');
  13392. if (octets.length === 4) {
  13393. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13394. poolInput.value = `${base}.10-${base}.254`;
  13395. }
  13396. }
  13397. }
  13398. function openAddDHCPServerModal() {
  13399. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13400. document.getElementById('dhcp-server-modal-id').value = '';
  13401. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13402. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13403. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13404. document.getElementById('dhcp-server-modal-comment').value = '';
  13405. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13406. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13407. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13408. const networks = state.dhcpNetworks || [];
  13409. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13410. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13411. if (defaultNet) {
  13412. onDHCPServerNetworkChange();
  13413. }
  13414. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13415. }
  13416. function openEditDHCPServerModal(id) {
  13417. const s = (state.dhcpServers || []).find(item => item.id === id);
  13418. if (!s) return;
  13419. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13420. document.getElementById('dhcp-server-modal-id').value = s.id;
  13421. document.getElementById('dhcp-server-modal-name').value = s.name;
  13422. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13423. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13424. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13425. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13426. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13427. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13428. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13429. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13430. }
  13431. function closeDHCPServerModal() {
  13432. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13433. }
  13434. async function submitSaveDHCPServer(e) {
  13435. e.preventDefault();
  13436. const id = document.getElementById('dhcp-server-modal-id').value;
  13437. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13438. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13439. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13440. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13441. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13442. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13443. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13444. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13445. try {
  13446. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13447. method: 'POST',
  13448. headers: { 'Content-Type': 'application/json' },
  13449. body: JSON.stringify({
  13450. id,
  13451. name,
  13452. interface: iface,
  13453. network,
  13454. address_pool: pool,
  13455. lease_time: leaseTime,
  13456. authoritative,
  13457. disabled,
  13458. comment
  13459. })
  13460. });
  13461. if (res.ok) {
  13462. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13463. closeDHCPServerModal();
  13464. loadDHCPServer(false);
  13465. fetchData(false);
  13466. } else {
  13467. const err = await res.text();
  13468. showToast('Error', err, 'error');
  13469. }
  13470. } catch (err) {
  13471. showToast('Error', err.message, 'error');
  13472. }
  13473. }
  13474. async function toggleDHCPServerState(id, disabled) {
  13475. try {
  13476. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13477. method: 'POST',
  13478. headers: { 'Content-Type': 'application/json' },
  13479. body: JSON.stringify({ disabled })
  13480. });
  13481. if (res.ok) {
  13482. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13483. loadDHCPServer(false);
  13484. fetchData(false);
  13485. }
  13486. } catch (err) {
  13487. showToast('Error', err.message, 'error');
  13488. }
  13489. }
  13490. async function deleteDHCPServer(id, name) {
  13491. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13492. try {
  13493. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13494. if (res.ok) {
  13495. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13496. loadDHCPServer(false);
  13497. fetchData(false);
  13498. }
  13499. } catch (err) {
  13500. showToast('Error', err.message, 'error');
  13501. }
  13502. }
  13503. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13504. function openAddDHCPNetworkModal() {
  13505. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13506. document.getElementById('dhcp-network-modal-id').value = '';
  13507. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13508. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13509. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13510. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13511. document.getElementById('dhcp-network-modal-netmask').value = '';
  13512. document.getElementById('dhcp-network-modal-comment').value = '';
  13513. renderDHCPNetworkOptionsCheckboxes([]);
  13514. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13515. }
  13516. function openEditDHCPNetworkModal(id) {
  13517. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13518. if (!n) return;
  13519. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13520. document.getElementById('dhcp-network-modal-id').value = n.id;
  13521. document.getElementById('dhcp-network-modal-address').value = n.address;
  13522. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13523. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13524. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13525. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13526. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13527. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13528. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13529. }
  13530. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13531. const container = document.getElementById('dhcp-network-modal-options-list');
  13532. if (!container) return;
  13533. container.innerHTML = '';
  13534. const opts = state.dhcpOptions || [];
  13535. if (opts.length === 0) {
  13536. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13537. return;
  13538. }
  13539. opts.forEach(o => {
  13540. const isChecked = selectedIds.includes(o.id);
  13541. const label = document.createElement('label');
  13542. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13543. label.innerHTML = `
  13544. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13545. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13546. `;
  13547. container.appendChild(label);
  13548. });
  13549. }
  13550. function closeDHCPNetworkModal() {
  13551. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13552. }
  13553. async function submitSaveDHCPNetwork(e) {
  13554. e.preventDefault();
  13555. const id = document.getElementById('dhcp-network-modal-id').value;
  13556. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13557. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13558. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13559. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13560. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13561. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13562. const selectedOpts = [];
  13563. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13564. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13565. try {
  13566. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13567. method: 'POST',
  13568. headers: { 'Content-Type': 'application/json' },
  13569. body: JSON.stringify({
  13570. id,
  13571. address,
  13572. gateway,
  13573. netmask,
  13574. dns_servers: dnsServers,
  13575. domain,
  13576. dhcp_options: selectedOpts,
  13577. comment
  13578. })
  13579. });
  13580. if (res.ok) {
  13581. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13582. closeDHCPNetworkModal();
  13583. loadDHCPServer(false);
  13584. fetchData(false);
  13585. } else {
  13586. const err = await res.text();
  13587. showToast('Error', err, 'error');
  13588. }
  13589. } catch (err) {
  13590. showToast('Error', err.message, 'error');
  13591. }
  13592. }
  13593. async function deleteDHCPNetwork(id, addr) {
  13594. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13595. try {
  13596. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13597. if (res.ok) {
  13598. showToast('Deleted', `Network ${addr} removed`, 'success');
  13599. loadDHCPServer(false);
  13600. fetchData(false);
  13601. }
  13602. } catch (err) {
  13603. showToast('Error', err.message, 'error');
  13604. }
  13605. }
  13606. // ==================== MODALS & ACTIONS: LEASES ====================
  13607. function openAddDHCPStaticLeaseModal() {
  13608. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13609. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13610. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13611. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13612. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13613. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13614. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13615. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13616. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13617. }
  13618. function closeDHCPStaticLeaseModal() {
  13619. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13620. }
  13621. async function submitSaveDHCPStaticLease(e) {
  13622. e.preventDefault();
  13623. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13624. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13625. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13626. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13627. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13628. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13629. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13630. try {
  13631. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13632. method: 'POST',
  13633. headers: { 'Content-Type': 'application/json' },
  13634. body: JSON.stringify({
  13635. id,
  13636. mac_address: mac,
  13637. address: ip,
  13638. hostname,
  13639. server,
  13640. comment,
  13641. disabled
  13642. })
  13643. });
  13644. if (res.ok) {
  13645. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13646. closeDHCPStaticLeaseModal();
  13647. loadDHCPServer(false);
  13648. fetchData(false);
  13649. } else {
  13650. const err = await res.text();
  13651. showToast('Error', err, 'error');
  13652. }
  13653. } catch (err) {
  13654. showToast('Error', err.message, 'error');
  13655. }
  13656. }
  13657. async function deleteDHCPStaticLease(id) {
  13658. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13659. try {
  13660. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13661. if (res.ok) {
  13662. showToast('Deleted', 'Static lease removed', 'success');
  13663. loadDHCPServer(false);
  13664. fetchData(false);
  13665. }
  13666. } catch (err) {
  13667. showToast('Error', err.message, 'error');
  13668. }
  13669. }
  13670. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13671. try {
  13672. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13673. method: 'POST',
  13674. headers: { 'Content-Type': 'application/json' },
  13675. body: JSON.stringify({
  13676. mac_address: mac,
  13677. address: ip,
  13678. hostname,
  13679. comment: comment || 'Converted to static'
  13680. })
  13681. });
  13682. if (res.ok) {
  13683. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13684. loadDHCPServer(false);
  13685. fetchData(false);
  13686. } else {
  13687. const err = await res.text();
  13688. showToast('Error', err, 'error');
  13689. }
  13690. } catch (err) {
  13691. showToast('Error', err.message, 'error');
  13692. }
  13693. }
  13694. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13695. function openAddDHCPOptionModal() {
  13696. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13697. document.getElementById('dhcp-option-modal-id').value = '';
  13698. document.getElementById('dhcp-option-modal-name').value = '';
  13699. document.getElementById('dhcp-option-modal-code').value = '';
  13700. document.getElementById('dhcp-option-modal-value').value = '';
  13701. document.getElementById('dhcp-option-modal-comment').value = '';
  13702. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13703. }
  13704. function openEditDHCPOptionModal(id) {
  13705. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13706. if (!o) return;
  13707. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13708. document.getElementById('dhcp-option-modal-id').value = o.id;
  13709. document.getElementById('dhcp-option-modal-name').value = o.name;
  13710. document.getElementById('dhcp-option-modal-code').value = o.code;
  13711. document.getElementById('dhcp-option-modal-value').value = o.value;
  13712. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13713. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13714. }
  13715. function closeDHCPOptionModal() {
  13716. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13717. }
  13718. async function submitSaveDHCPOption(e) {
  13719. e.preventDefault();
  13720. const id = document.getElementById('dhcp-option-modal-id').value;
  13721. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13722. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13723. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13724. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13725. try {
  13726. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13727. method: 'POST',
  13728. headers: { 'Content-Type': 'application/json' },
  13729. body: JSON.stringify({ id, name, code, value, comment })
  13730. });
  13731. if (res.ok) {
  13732. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13733. closeDHCPOptionModal();
  13734. loadDHCPServer(false);
  13735. fetchData(false);
  13736. } else {
  13737. const err = await res.text();
  13738. showToast('Error', err, 'error');
  13739. }
  13740. } catch (err) {
  13741. showToast('Error', err.message, 'error');
  13742. }
  13743. }
  13744. async function deleteDHCPOption(id, name) {
  13745. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13746. try {
  13747. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13748. if (res.ok) {
  13749. showToast('Deleted', `Option ${name} removed`, 'success');
  13750. loadDHCPServer(false);
  13751. fetchData(false);
  13752. }
  13753. } catch (err) {
  13754. showToast('Error', err.message, 'error');
  13755. }
  13756. }
  13757. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13758. function openDHCPServerSetupModal() {
  13759. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13760. onDHCPWizardIfaceChange();
  13761. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13762. }
  13763. function closeDHCPServerSetupModal() {
  13764. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13765. }
  13766. function onDHCPWizardIfaceChange() {
  13767. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13768. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13769. let ip = '192.168.88.1';
  13770. let prefix = '24';
  13771. if (iface && iface.ip_address) {
  13772. const parts = iface.ip_address.split('/');
  13773. ip = parts[0];
  13774. if (parts.length > 1) prefix = parts[1];
  13775. }
  13776. // Calculate subnet base (e.g. 192.168.88.0/24)
  13777. const ipParts = ip.split('.');
  13778. if (ipParts.length === 4) {
  13779. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13780. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13781. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13782. document.getElementById('dhcp-wizard-gateway').value = ip;
  13783. document.getElementById('dhcp-wizard-pool').value = pool;
  13784. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13785. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13786. }
  13787. }
  13788. async function submitDHCPServerSetupWizard(e) {
  13789. e.preventDefault();
  13790. const iface = document.getElementById('dhcp-wizard-iface').value;
  13791. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13792. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13793. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13794. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13795. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13796. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13797. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13798. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13799. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13800. try {
  13801. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13802. method: 'POST',
  13803. headers: { 'Content-Type': 'application/json' },
  13804. body: JSON.stringify({
  13805. interface: iface,
  13806. address_space: space,
  13807. gateway: gw,
  13808. address_pool: pool,
  13809. dns_servers: dnsServers,
  13810. lease_time: leaseTime,
  13811. ntp_servers: ntpServers,
  13812. next_server: tftp
  13813. })
  13814. });
  13815. if (res.ok) {
  13816. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13817. closeDHCPServerSetupModal();
  13818. loadDHCPServer(false);
  13819. fetchData(false);
  13820. } else {
  13821. const err = await res.text();
  13822. showToast('Error', err, 'error');
  13823. }
  13824. } catch (err) {
  13825. showToast('Error', err.message, 'error');
  13826. }
  13827. }
  13828. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13829. const sel = document.getElementById(elemId);
  13830. if (!sel) return;
  13831. sel.innerHTML = '<option value="">Select interface...</option>';
  13832. const ifaces = state.interfaces || [];
  13833. ifaces.forEach(i => {
  13834. if (i.name === 'lo') return;
  13835. const opt = document.createElement('option');
  13836. opt.value = i.name;
  13837. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13838. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13839. if (i.name === selectedVal) opt.selected = true;
  13840. sel.appendChild(opt);
  13841. });
  13842. }
  13843. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13844. function initTableSorting() {
  13845. document.querySelectorAll('table').forEach(setupSortableTable);
  13846. }
  13847. function setupSortableTable(table) {
  13848. const thead = table.querySelector('thead');
  13849. const tbody = table.querySelector('tbody');
  13850. if (!thead || !tbody) return;
  13851. const headerRows = thead.querySelectorAll('tr');
  13852. if (headerRows.length === 0) return;
  13853. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13854. ths.forEach((th, colIdx) => {
  13855. if (th._sortBound) return;
  13856. th._sortBound = true;
  13857. const rawText = th.innerText.trim().toLowerCase();
  13858. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13859. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13860. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13861. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13862. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13863. return;
  13864. }
  13865. th.classList.add('table-sortable', 'group');
  13866. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13867. let icon = th.querySelector('.table-sort-icon');
  13868. if (!icon) {
  13869. icon = document.createElement('span');
  13870. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13871. icon.innerHTML = '⇅';
  13872. th.appendChild(icon);
  13873. }
  13874. th.addEventListener('click', (e) => {
  13875. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13876. handleHeaderClick(table, th, colIdx);
  13877. });
  13878. });
  13879. if (!tbody._sortObserved) {
  13880. tbody._sortObserved = true;
  13881. let sortDebounceTimer = null;
  13882. const observer = new MutationObserver((mutations) => {
  13883. if (tbody._isSorting) return;
  13884. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13885. if (!hasChildChanges) return;
  13886. clearTimeout(sortDebounceTimer);
  13887. sortDebounceTimer = setTimeout(() => {
  13888. if (tbody._isSorting) return;
  13889. if (table._activeSort && table._activeSort.dir !== 'none') {
  13890. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13891. } else {
  13892. tagOriginalRowOrder(tbody);
  13893. }
  13894. }, 50);
  13895. });
  13896. tbody._sortObserver = observer;
  13897. observer.observe(tbody, { childList: true });
  13898. }
  13899. tagOriginalRowOrder(tbody);
  13900. }
  13901. function tagOriginalRowOrder(tbody) {
  13902. let idx = 0;
  13903. Array.from(tbody.children).forEach(tr => {
  13904. if (!tr.querySelector('td[colspan]')) {
  13905. if (!tr.hasAttribute('data-orig-idx')) {
  13906. tr.setAttribute('data-orig-idx', idx++);
  13907. }
  13908. }
  13909. });
  13910. }
  13911. function handleHeaderClick(table, th, colIdx) {
  13912. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13913. let newDir = 'asc';
  13914. if (currentSort.colIdx === colIdx) {
  13915. if (currentSort.dir === 'asc') newDir = 'desc';
  13916. else if (currentSort.dir === 'desc') newDir = 'none';
  13917. else newDir = 'asc';
  13918. } else {
  13919. newDir = 'asc';
  13920. }
  13921. table._activeSort = { colIdx, dir: newDir };
  13922. updateHeaderIcons(table, colIdx, newDir);
  13923. applyTableSort(table, colIdx, newDir, true);
  13924. }
  13925. function updateHeaderIcons(table, activeColIdx, dir) {
  13926. const thead = table.querySelector('thead');
  13927. if (!thead) return;
  13928. const ths = thead.querySelectorAll('th');
  13929. ths.forEach((th, idx) => {
  13930. const icon = th.querySelector('.table-sort-icon');
  13931. if (!icon) return;
  13932. if (idx === activeColIdx && dir !== 'none') {
  13933. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13934. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13935. th.classList.add('table-sorted-active');
  13936. } else {
  13937. icon.innerHTML = '⇅';
  13938. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13939. th.classList.remove('table-sorted-active');
  13940. }
  13941. });
  13942. }
  13943. function applyTableSort(table, colIdx, dir, userInitiated) {
  13944. const tbody = table.querySelector('tbody');
  13945. if (!tbody || tbody.children.length <= 1) return;
  13946. tbody._isSorting = true;
  13947. tagOriginalRowOrder(tbody);
  13948. // Group parent rows and any attached drawer/sub-rows
  13949. const groups = [];
  13950. let currentGroup = null;
  13951. Array.from(tbody.children).forEach(tr => {
  13952. if (tr.querySelector('td[colspan]')) {
  13953. if (currentGroup) {
  13954. currentGroup.subRows.push(tr);
  13955. } else {
  13956. groups.push({ mainRow: tr, subRows: [] });
  13957. }
  13958. } else {
  13959. currentGroup = { mainRow: tr, subRows: [] };
  13960. groups.push(currentGroup);
  13961. }
  13962. });
  13963. if (dir === 'none') {
  13964. groups.sort((a, b) => {
  13965. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13966. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13967. return idxA - idxB;
  13968. });
  13969. } else {
  13970. groups.sort((a, b) => {
  13971. const cellA = a.mainRow.children[colIdx];
  13972. const cellB = b.mainRow.children[colIdx];
  13973. const res = compareTableCells(cellA, cellB);
  13974. return dir === 'asc' ? res : -res;
  13975. });
  13976. }
  13977. // Check if rows are already in correct order to avoid modifying DOM
  13978. let alreadyOrdered = true;
  13979. let childIdx = 0;
  13980. for (const g of groups) {
  13981. if (tbody.children[childIdx] !== g.mainRow) {
  13982. alreadyOrdered = false;
  13983. break;
  13984. }
  13985. childIdx++;
  13986. for (const sub of g.subRows) {
  13987. if (tbody.children[childIdx] !== sub) {
  13988. alreadyOrdered = false;
  13989. break;
  13990. }
  13991. childIdx++;
  13992. }
  13993. }
  13994. if (alreadyOrdered) {
  13995. tbody._isSorting = false;
  13996. return;
  13997. }
  13998. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13999. if (tbody._sortObserver) {
  14000. tbody._sortObserver.disconnect();
  14001. }
  14002. // Re-append rows in sorted order
  14003. groups.forEach(g => {
  14004. tbody.appendChild(g.mainRow);
  14005. g.subRows.forEach(sub => tbody.appendChild(sub));
  14006. });
  14007. // Drain any queued mutations and re-connect observer
  14008. if (tbody._sortObserver) {
  14009. tbody._sortObserver.takeRecords();
  14010. tbody._sortObserver.observe(tbody, { childList: true });
  14011. }
  14012. tbody._isSorting = false;
  14013. }
  14014. function getCellRawText(cell) {
  14015. if (!cell) return '';
  14016. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14017. const input = cell.querySelector('input, select');
  14018. if (input) {
  14019. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14020. return input.value;
  14021. }
  14022. return cell.innerText.trim();
  14023. }
  14024. function parseTrafficToNumber(str) {
  14025. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14026. if (!m) return null;
  14027. const num = parseFloat(m[1].replace(/,/g, ''));
  14028. if (isNaN(num)) return null;
  14029. const unit = m[2].toUpperCase();
  14030. let mult = 1;
  14031. if (unit.startsWith('K')) mult = 1024;
  14032. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14033. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14034. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14035. return num * mult;
  14036. }
  14037. function parseIpToNumber(str) {
  14038. const clean = str.replace(/^[!~]/, '').trim();
  14039. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14040. if (!m) return null;
  14041. const o1 = parseInt(m[1], 10);
  14042. const o2 = parseInt(m[2], 10);
  14043. const o3 = parseInt(m[3], 10);
  14044. const o4 = parseInt(m[4], 10);
  14045. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14046. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14047. }
  14048. function parseCompoundPackets(str) {
  14049. const m = str.match(/^([\d,]+)p/);
  14050. if (!m) return null;
  14051. return parseInt(m[1].replace(/,/g, ''), 10);
  14052. }
  14053. function compareTableCells(cellA, cellB) {
  14054. const a = getCellRawText(cellA);
  14055. const b = getCellRawText(cellB);
  14056. if (a === '' && b !== '') return 1;
  14057. if (b === '' && a !== '') return -1;
  14058. if (a === b) return 0;
  14059. // 1. IP Addresses / CIDR
  14060. const ipA = parseIpToNumber(a);
  14061. const ipB = parseIpToNumber(b);
  14062. if (ipA !== null && ipB !== null) return ipA - ipB;
  14063. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14064. const pktA = parseCompoundPackets(a);
  14065. const pktB = parseCompoundPackets(b);
  14066. if (pktA !== null && pktB !== null) return pktA - pktB;
  14067. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14068. const trafA = parseTrafficToNumber(a);
  14069. const trafB = parseTrafficToNumber(b);
  14070. if (trafA !== null && trafB !== null) return trafA - trafB;
  14071. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14072. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14073. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14074. const numA = Number(cleanNumA);
  14075. const numB = Number(cleanNumB);
  14076. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14077. return numA - numB;
  14078. }
  14079. // 5. Natural case-insensitive string compare
  14080. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14081. }
  14082. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14083. async function loadVRRP(showToastNotification = false) {
  14084. try {
  14085. const [instRes, sumRes] = await Promise.all([
  14086. fetch(`${API_BASE}/vrrp/instances`),
  14087. fetch(`${API_BASE}/vrrp/summary`)
  14088. ]);
  14089. if (instRes.ok) {
  14090. state.vrrpInstances = await instRes.json();
  14091. renderVRRP();
  14092. }
  14093. if (sumRes.ok) {
  14094. state.vrrpSummary = await sumRes.json();
  14095. renderVRRPSummary();
  14096. }
  14097. if (showToastNotification) {
  14098. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14099. }
  14100. } catch (err) {
  14101. console.error('Failed to load VRRP:', err);
  14102. }
  14103. }
  14104. function renderVRRPSummary() {
  14105. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14106. const elTotal = document.getElementById('vrrp-stat-total');
  14107. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14108. const elMaster = document.getElementById('vrrp-stat-master');
  14109. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14110. const elBackup = document.getElementById('vrrp-stat-backup');
  14111. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14112. const bCount = document.getElementById('badge-vrrp-count');
  14113. if (bCount) bCount.innerText = s.total_instances || 0;
  14114. const dot = document.getElementById('badge-vrrp-dot');
  14115. if (dot) {
  14116. if (s.master_instances > 0) {
  14117. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14118. } else if (s.backup_instances > 0) {
  14119. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14120. } else {
  14121. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14122. }
  14123. }
  14124. }
  14125. function renderVRRP() {
  14126. const tbody = document.getElementById('vrrp-table-tbody');
  14127. const empty = document.getElementById('vrrp-table-empty');
  14128. if (!tbody) return;
  14129. tbody.innerHTML = '';
  14130. const instances = state.vrrpInstances || [];
  14131. if (instances.length === 0) {
  14132. empty?.classList.remove('hidden');
  14133. return;
  14134. }
  14135. empty?.classList.add('hidden');
  14136. instances.forEach(inst => {
  14137. const tr = document.createElement('tr');
  14138. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14139. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14140. 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>`;
  14141. if (inst.disabled) {
  14142. 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>`;
  14143. } else if (inst.state === 'MASTER') {
  14144. 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>`;
  14145. } else if (inst.state === 'BACKUP') {
  14146. 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>`;
  14147. } else if (inst.state === 'FAULT') {
  14148. 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>`;
  14149. }
  14150. // Render State Badge
  14151. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14152. if (!inst.disabled) {
  14153. if (inst.state === 'MASTER') {
  14154. 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>`;
  14155. } else if (inst.state === 'BACKUP') {
  14156. 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>`;
  14157. } else if (inst.state === 'FAULT') {
  14158. 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>`;
  14159. }
  14160. }
  14161. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14162. tr.innerHTML = `
  14163. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14164. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14165. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14166. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14167. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14168. <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>
  14169. <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>
  14170. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14171. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14172. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14173. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14174. <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>
  14175. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14176. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14177. </td>
  14178. `;
  14179. tbody.appendChild(tr);
  14180. });
  14181. }
  14182. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14183. const sel = document.getElementById(elemId);
  14184. if (!sel) return;
  14185. sel.innerHTML = '<option value="">Select interface...</option>';
  14186. const ifaces = state.interfaces || [];
  14187. ifaces.forEach(i => {
  14188. const opt = document.createElement('option');
  14189. opt.value = i.name;
  14190. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14191. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14192. sel.appendChild(opt);
  14193. });
  14194. }
  14195. function openAddVRRPModal() {
  14196. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14197. document.getElementById('modal-vrrp-id').value = '';
  14198. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14199. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14200. document.getElementById('modal-vrrp-priority').value = 100;
  14201. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14202. document.getElementById('modal-vrrp-version').value = '3';
  14203. document.getElementById('modal-vrrp-interval').value = 1;
  14204. document.getElementById('modal-vrrp-authtype').value = 'none';
  14205. document.getElementById('modal-vrrp-authpass').value = '';
  14206. document.getElementById('modal-vrrp-comment').value = '';
  14207. document.getElementById('modal-vrrp-preempt').checked = true;
  14208. document.getElementById('modal-vrrp-disabled').checked = false;
  14209. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14210. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14211. }
  14212. function openEditVRRPModal(id) {
  14213. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14214. if (!inst) return;
  14215. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14216. document.getElementById('modal-vrrp-id').value = inst.id;
  14217. document.getElementById('modal-vrrp-name').value = inst.name;
  14218. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14219. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14220. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14221. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14222. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14223. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14224. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14225. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14226. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14227. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14228. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14229. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14230. }
  14231. function closeVRRPModal() {
  14232. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14233. }
  14234. async function submitSaveVRRP(e) {
  14235. e.preventDefault();
  14236. const id = document.getElementById('modal-vrrp-id').value;
  14237. const name = document.getElementById('modal-vrrp-name').value.trim();
  14238. const iface = document.getElementById('modal-vrrp-iface').value;
  14239. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14240. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14241. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14242. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14243. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14244. const authType = document.getElementById('modal-vrrp-authtype').value;
  14245. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14246. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14247. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14248. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14249. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14250. try {
  14251. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14252. method: 'POST',
  14253. headers: { 'Content-Type': 'application/json' },
  14254. body: JSON.stringify({
  14255. id,
  14256. name,
  14257. interface: iface,
  14258. vrid,
  14259. priority,
  14260. virtual_ips: vips,
  14261. version,
  14262. interval,
  14263. auth_type: authType,
  14264. auth_password: authPass,
  14265. comment,
  14266. preempt,
  14267. disabled
  14268. })
  14269. });
  14270. if (res.ok) {
  14271. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14272. closeVRRPModal();
  14273. loadVRRP(false);
  14274. fetchData(false);
  14275. } else {
  14276. const err = await res.text();
  14277. showToast('Error', err, 'error');
  14278. }
  14279. } catch (err) {
  14280. showToast('Error', err.message, 'error');
  14281. }
  14282. }
  14283. async function deleteVRRP(id, name) {
  14284. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14285. try {
  14286. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14287. if (res.ok) {
  14288. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14289. loadVRRP(false);
  14290. fetchData(false);
  14291. } else {
  14292. const err = await res.text();
  14293. showToast('Error', err, 'error');
  14294. }
  14295. } catch (err) {
  14296. showToast('Error', err.message, 'error');
  14297. }
  14298. }
  14299. async function toggleVRRPState(id, disabled) {
  14300. try {
  14301. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14302. method: 'POST',
  14303. headers: { 'Content-Type': 'application/json' },
  14304. body: JSON.stringify({ disabled })
  14305. });
  14306. if (res.ok) {
  14307. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14308. loadVRRP(false);
  14309. fetchData(false);
  14310. } else {
  14311. const err = await res.text();
  14312. showToast('Error', err, 'error');
  14313. }
  14314. } catch (err) {
  14315. showToast('Error', err.message, 'error');
  14316. }
  14317. }
  14318. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14319. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14320. let docSortDebounce = null;
  14321. const docTableObserver = new MutationObserver((mutations) => {
  14322. let needsInit = false;
  14323. for (const m of mutations) {
  14324. for (const node of m.addedNodes) {
  14325. if (node.nodeType === 1) {
  14326. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14327. needsInit = true;
  14328. break;
  14329. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14330. needsInit = true;
  14331. break;
  14332. }
  14333. }
  14334. }
  14335. if (needsInit) break;
  14336. }
  14337. if (needsInit) {
  14338. clearTimeout(docSortDebounce);
  14339. docSortDebounce = setTimeout(initTableSorting, 100);
  14340. }
  14341. });
  14342. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14343. }
  14344. // =========================================================================
  14345. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14346. // =========================================================================
  14347. const bwtestState = {
  14348. running: false,
  14349. pollTimer: null,
  14350. eventSource: null,
  14351. chartPoints: [],
  14352. maxChartPoints: 60,
  14353. serverConfig: null,
  14354. peakTx: 0,
  14355. peakRx: 0,
  14356. targetDuration: 10,
  14357. lastSampleElapsed: -1,
  14358. sessionID: null
  14359. };
  14360. async function loadBwTestView() {
  14361. resizeBwTestCanvas();
  14362. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14363. }
  14364. async function fetchBwTestServerStatus() {
  14365. try {
  14366. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14367. if (!res.ok) return;
  14368. const s = await res.json();
  14369. bwtestState.serverConfig = s;
  14370. // Update indicator and badges
  14371. const indicator = document.getElementById('bwtest-server-indicator');
  14372. const badge = document.getElementById('bwtest-server-badge');
  14373. const sideBadge = document.getElementById('badge-bwtest-server');
  14374. if (s.enabled && s.running) {
  14375. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14376. if (badge) {
  14377. badge.innerText = `Port ${s.port} (Active)`;
  14378. badge.className = 'text-emerald-400 font-bold';
  14379. }
  14380. if (sideBadge) {
  14381. sideBadge.innerText = s.port;
  14382. 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';
  14383. }
  14384. } else {
  14385. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14386. if (badge) {
  14387. badge.innerText = `Disabled`;
  14388. badge.className = 'text-slate-500 font-bold';
  14389. }
  14390. if (sideBadge) {
  14391. sideBadge.innerText = 'Off';
  14392. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14393. }
  14394. }
  14395. // Modal fields
  14396. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14397. const serverModal = document.getElementById('modal-bwtest-server');
  14398. const editing = serverModal && !serverModal.classList.contains('hidden');
  14399. if (toggle && !editing) toggle.checked = !!s.enabled;
  14400. const portInp = document.getElementById('bwtest-server-port-input');
  14401. if (portInp && !editing) portInp.value = s.port || 2000;
  14402. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14403. if (actSess) actSess.innerText = s.active_sessions || 0;
  14404. const totServ = document.getElementById('bwtest-modal-total-served');
  14405. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14406. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14407. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14408. } catch (err) {
  14409. console.error('Failed to fetch BwTest server status:', err);
  14410. }
  14411. }
  14412. function openBwTestServerModal() {
  14413. const cfg = bwtestState.serverConfig;
  14414. if (cfg) {
  14415. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14416. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14417. }
  14418. fetchBwTestServerStatus();
  14419. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14420. }
  14421. function closeBwTestServerModal() {
  14422. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14423. }
  14424. async function submitBwTestServerSettings(e) {
  14425. e.preventDefault();
  14426. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14427. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14428. try {
  14429. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14430. method: 'POST',
  14431. headers: { 'Content-Type': 'application/json' },
  14432. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14433. });
  14434. if (!res.ok) {
  14435. const err = await res.json();
  14436. throw new Error(err.error || 'Failed to update server configuration');
  14437. }
  14438. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14439. closeBwTestServerModal();
  14440. fetchBwTestServerStatus();
  14441. } catch (err) {
  14442. showToast('Server Configuration Error', err.message, 'error');
  14443. }
  14444. }
  14445. function setBwTestTarget(target) {
  14446. const inp = document.getElementById('bwtest-input-target');
  14447. if (inp) inp.value = target;
  14448. }
  14449. function setBwTestProtocol(proto) {
  14450. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14451. if (hiddenInp) hiddenInp.value = proto;
  14452. const btnUdp = document.getElementById('bwtest-proto-udp');
  14453. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14454. const badge = document.getElementById('bwtest-proto-badge');
  14455. const pktField = document.getElementById('bwtest-field-pktsize');
  14456. 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';
  14457. 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';
  14458. 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';
  14459. if (proto === 'udp') {
  14460. if (btnUdp) {
  14461. btnUdp.className = activeUdpCls;
  14462. const dot = btnUdp.querySelector('span');
  14463. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14464. }
  14465. if (btnTcp) {
  14466. btnTcp.className = inactiveCls;
  14467. const dot = btnTcp.querySelector('span');
  14468. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14469. }
  14470. if (badge) {
  14471. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14472. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14473. }
  14474. if (pktField) pktField.classList.remove('opacity-40');
  14475. } else {
  14476. if (btnUdp) {
  14477. btnUdp.className = inactiveCls;
  14478. const dot = btnUdp.querySelector('span');
  14479. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14480. }
  14481. if (btnTcp) {
  14482. btnTcp.className = activeTcpCls;
  14483. const dot = btnTcp.querySelector('span');
  14484. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14485. }
  14486. if (badge) {
  14487. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14488. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14489. }
  14490. if (pktField) pktField.classList.add('opacity-40');
  14491. }
  14492. }
  14493. function setBwTestDirection(dir) {
  14494. const hiddenInp = document.getElementById('bwtest-input-direction');
  14495. if (hiddenInp) hiddenInp.value = dir;
  14496. const btnBoth = document.getElementById('bwtest-dir-both');
  14497. const btnTx = document.getElementById('bwtest-dir-tx');
  14498. const btnRx = document.getElementById('bwtest-dir-rx');
  14499. 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';
  14500. 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';
  14501. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14502. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14503. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14504. }
  14505. function setBwTestLimit(bps) {
  14506. const sel = document.getElementById('bwtest-input-limit');
  14507. if (sel) sel.value = String(bps);
  14508. }
  14509. async function checkActiveBwTest() {
  14510. try {
  14511. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14512. if (!res.ok) return;
  14513. const st = await res.json();
  14514. if (st.running) {
  14515. setBwTestRunningUI(true);
  14516. processBwTestStatus(st);
  14517. startBwTestTelemetry();
  14518. }
  14519. } catch (err) {
  14520. console.error('Failed to check active BwTest:', err);
  14521. }
  14522. }
  14523. async function startBwTest(e) {
  14524. if (e && e.preventDefault) e.preventDefault();
  14525. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14526. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14527. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14528. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14529. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14530. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14531. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14532. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14533. bwtestState.targetDuration = duration;
  14534. bwtestState.chartPoints = [];
  14535. bwtestState.peakTx = 0;
  14536. bwtestState.peakRx = 0;
  14537. bwtestState.lastSampleElapsed = -1;
  14538. bwtestState.sessionID = null;
  14539. // Clear UI elements
  14540. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14541. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14542. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14543. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14544. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14545. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14546. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14547. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14548. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14549. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14550. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14551. const tbody = document.getElementById('bwtest-samples-tbody');
  14552. if (tbody) tbody.innerHTML = '';
  14553. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14554. setBwTestRunningUI(true);
  14555. try {
  14556. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14557. method: 'POST',
  14558. headers: { 'Content-Type': 'application/json' },
  14559. body: JSON.stringify({
  14560. target,
  14561. port,
  14562. direction,
  14563. protocol,
  14564. bandwidth_limit,
  14565. packet_size,
  14566. streams,
  14567. duration
  14568. })
  14569. });
  14570. if (!res.ok) {
  14571. const err = await res.json();
  14572. throw new Error(err.error || 'Failed to start bandwidth test');
  14573. }
  14574. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14575. startBwTestTelemetry();
  14576. } catch (err) {
  14577. setBwTestRunningUI(false);
  14578. showToast('Start Failed', err.message, 'error');
  14579. }
  14580. }
  14581. function setBwTestRunningUI(running) {
  14582. bwtestState.running = running;
  14583. const startBtn = document.getElementById('bwtest-btn-start');
  14584. const stopBtn = document.getElementById('bwtest-btn-stop');
  14585. const badge = document.getElementById('bwtest-run-status-badge');
  14586. const ph = document.getElementById('bwtest-chart-placeholder');
  14587. if (running) {
  14588. if (startBtn) {
  14589. startBtn.disabled = true;
  14590. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14591. }
  14592. if (stopBtn) {
  14593. stopBtn.disabled = false;
  14594. stopBtn.classList.remove('opacity-40');
  14595. }
  14596. if (badge) {
  14597. badge.innerText = 'TESTING...';
  14598. 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';
  14599. }
  14600. if (ph) ph.style.display = 'none';
  14601. } else {
  14602. if (startBtn) {
  14603. startBtn.disabled = false;
  14604. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14605. }
  14606. if (stopBtn) {
  14607. stopBtn.disabled = true;
  14608. stopBtn.classList.add('opacity-40');
  14609. }
  14610. if (badge) {
  14611. badge.innerText = 'IDLE';
  14612. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14613. }
  14614. }
  14615. }
  14616. async function stopBwTest() {
  14617. try {
  14618. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14619. if (!res.ok) throw new Error(await responseError(res));
  14620. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14621. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14622. } catch (err) {
  14623. showToast('Stop Failed', err.message, 'error');
  14624. }
  14625. }
  14626. async function responseError(res) {
  14627. const text = await res.text();
  14628. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14629. catch { return text || `HTTP ${res.status}`; }
  14630. }
  14631. function processBwTestStatus(st) {
  14632. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14633. bwtestState.sessionID = st.session_id;
  14634. bwtestState.lastSampleElapsed = -1;
  14635. }
  14636. for (const sample of st.recent_samples || []) {
  14637. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14638. handleBwTestSample(sample);
  14639. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14640. }
  14641. }
  14642. if (!st.running) {
  14643. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14644. bwtestState.pollTimer = null;
  14645. setBwTestRunningUI(false);
  14646. handleBwTestFinish(st.summary, st.error);
  14647. }
  14648. }
  14649. function startBwTestTelemetry() {
  14650. if (!state.currentUser) return;
  14651. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14652. let busy = false;
  14653. const poll = async () => {
  14654. if (busy || !state.currentUser || document.hidden) return;
  14655. busy = true;
  14656. try {
  14657. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14658. if (!res.ok) throw new Error(await responseError(res));
  14659. processBwTestStatus(await res.json());
  14660. } catch (err) {
  14661. console.error('BwTest polling error:', err);
  14662. } finally { busy = false; }
  14663. };
  14664. bwtestState.pollTimer = setInterval(poll, 400);
  14665. poll();
  14666. }
  14667. function handleBwTestSample(s) {
  14668. if (!s) return;
  14669. const payloadHint = document.getElementById('bwtest-effective-payload');
  14670. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14671. const txMbps = s.tx_mbps || 0;
  14672. const rxMbps = s.rx_mbps || 0;
  14673. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14674. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14675. // KPI updates
  14676. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14677. if (elTx) {
  14678. elTx.innerText = txMbps.toFixed(2);
  14679. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14680. }
  14681. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14682. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14683. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14684. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14685. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14686. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14687. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14688. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14689. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14690. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14691. const elLoss = document.getElementById('bwtest-stat-loss');
  14692. if (elLoss) {
  14693. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14694. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14695. }
  14696. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14697. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14698. const elJitter = document.getElementById('bwtest-stat-jitter');
  14699. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14700. const elTime = document.getElementById('bwtest-stat-time');
  14701. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14702. const elData = document.getElementById('bwtest-stat-data');
  14703. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14704. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14705. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14706. // Append point to chart buffer
  14707. bwtestState.chartPoints.push({
  14708. elapsed: s.elapsed_sec || 0,
  14709. tx: txMbps,
  14710. rx: rxMbps
  14711. });
  14712. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14713. bwtestState.chartPoints.shift();
  14714. }
  14715. drawBwTestChart();
  14716. // Add row to breakdown table
  14717. const tbody = document.getElementById('bwtest-samples-tbody');
  14718. if (tbody) {
  14719. const tr = document.createElement('tr');
  14720. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14721. tr.innerHTML = `
  14722. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14723. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14724. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14725. <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>
  14726. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14727. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14728. `;
  14729. tbody.insertBefore(tr, tbody.firstChild);
  14730. const countEl = document.getElementById('bwtest-sample-count');
  14731. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14732. }
  14733. }
  14734. function handleBwTestFinish(summary, error) {
  14735. const badge = document.getElementById('bwtest-run-status-badge');
  14736. if (error) {
  14737. showToast('Benchmark Error', error, 'error');
  14738. if (badge) {
  14739. badge.innerText = 'ERROR';
  14740. 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';
  14741. }
  14742. } else if (summary) {
  14743. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14744. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14745. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14746. if (badge) {
  14747. badge.innerText = 'COMPLETED';
  14748. 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';
  14749. }
  14750. }
  14751. loadBwTestHistory();
  14752. fetchBwTestServerStatus();
  14753. }
  14754. function resizeBwTestCanvas() {
  14755. const canvas = document.getElementById('bwtest-chart');
  14756. if (!canvas || !canvas.parentElement) return;
  14757. const rect = canvas.parentElement.getBoundingClientRect();
  14758. const dpr = window.devicePixelRatio || 1;
  14759. canvas.width = rect.width * dpr;
  14760. canvas.height = rect.height * dpr;
  14761. const ctx = canvas.getContext('2d');
  14762. ctx.scale(dpr, dpr);
  14763. drawBwTestChart();
  14764. }
  14765. window.addEventListener('resize', () => {
  14766. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14767. });
  14768. function drawBwTestChart() {
  14769. const canvas = document.getElementById('bwtest-chart');
  14770. if (!canvas) return;
  14771. const ctx = canvas.getContext('2d');
  14772. const dpr = window.devicePixelRatio || 1;
  14773. const width = canvas.width / dpr;
  14774. const height = canvas.height / dpr;
  14775. ctx.clearRect(0, 0, width, height);
  14776. const points = bwtestState.chartPoints;
  14777. if (!points || points.length === 0) return;
  14778. // Determine scale ceiling
  14779. let maxRate = 10;
  14780. for (const p of points) {
  14781. if (p.tx > maxRate) maxRate = p.tx;
  14782. if (p.rx > maxRate) maxRate = p.rx;
  14783. }
  14784. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14785. const paddingLeft = 55;
  14786. const paddingBottom = 24;
  14787. const paddingTop = 12;
  14788. const paddingRight = 16;
  14789. const chartW = width - paddingLeft - paddingRight;
  14790. const chartH = height - paddingTop - paddingBottom;
  14791. // Grid Lines and Y-Axis labels
  14792. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14793. ctx.lineWidth = 1;
  14794. ctx.fillStyle = '#94a3b8';
  14795. ctx.font = '10px monospace';
  14796. ctx.textAlign = 'right';
  14797. const gridSteps = 4;
  14798. for (let i = 0; i <= gridSteps; i++) {
  14799. const val = (maxRate / gridSteps) * i;
  14800. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14801. ctx.beginPath();
  14802. ctx.moveTo(paddingLeft, y);
  14803. ctx.lineTo(width - paddingRight, y);
  14804. ctx.stroke();
  14805. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14806. }
  14807. // Draw TX Line (Cyan #22d3ee)
  14808. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14809. // Draw RX Line (Purple #a855f7)
  14810. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14811. }
  14812. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14813. if (points.length < 2) return;
  14814. const stepX = w / Math.max(points.length - 1, 1);
  14815. // Gradient area fill
  14816. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14817. grad.addColorStop(0, fillColor);
  14818. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14819. ctx.beginPath();
  14820. points.forEach((p, idx) => {
  14821. const x = left + idx * stepX;
  14822. const val = valFn(p);
  14823. const y = top + h - (val / maxVal) * h;
  14824. if (idx === 0) {
  14825. ctx.moveTo(x, y);
  14826. } else {
  14827. ctx.lineTo(x, y);
  14828. }
  14829. });
  14830. // Complete path for fill
  14831. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14832. ctx.lineTo(left, top + h);
  14833. ctx.closePath();
  14834. ctx.fillStyle = grad;
  14835. ctx.fill();
  14836. // Draw line stroke
  14837. ctx.beginPath();
  14838. ctx.lineWidth = 2.5;
  14839. ctx.strokeStyle = strokeColor;
  14840. points.forEach((p, idx) => {
  14841. const x = left + idx * stepX;
  14842. const val = valFn(p);
  14843. const y = top + h - (val / maxVal) * h;
  14844. if (idx === 0) {
  14845. ctx.moveTo(x, y);
  14846. } else {
  14847. ctx.lineTo(x, y);
  14848. }
  14849. });
  14850. ctx.stroke();
  14851. // Draw end point halo
  14852. const lastP = points[points.length - 1];
  14853. const lastX = left + (points.length - 1) * stepX;
  14854. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14855. ctx.fillStyle = strokeColor;
  14856. ctx.beginPath();
  14857. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14858. ctx.fill();
  14859. }
  14860. async function loadBwTestHistory() {
  14861. try {
  14862. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14863. if (!res.ok) return;
  14864. const list = await res.json();
  14865. renderBwTestHistory(Array.isArray(list) ? list : []);
  14866. } catch (err) {
  14867. console.error('Failed to load BwTest history:', err);
  14868. }
  14869. }
  14870. function renderBwTestHistory(list) {
  14871. const tbody = document.getElementById('bwtest-history-tbody');
  14872. if (!tbody) return;
  14873. if (list.length === 0) {
  14874. 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>`;
  14875. return;
  14876. }
  14877. tbody.innerHTML = '';
  14878. list.forEach(item => {
  14879. const s = item.summary || {};
  14880. const tr = document.createElement('tr');
  14881. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14882. const dirBadge = item.direction === 'both'
  14883. ? `<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>`
  14884. : item.direction === 'tx'
  14885. ? `<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>`
  14886. : `<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>`;
  14887. const protoBadge = item.protocol === 'tcp'
  14888. ? `<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>`
  14889. : `<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>`;
  14890. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14891. tr.innerHTML = `
  14892. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14893. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14894. <td class="py-2.5 px-4">${protoBadge}</td>
  14895. <td class="py-2.5 px-4">${dirBadge}</td>
  14896. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14897. <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>
  14898. <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>
  14899. <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>
  14900. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14901. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14902. `;
  14903. tbody.appendChild(tr);
  14904. });
  14905. }
  14906. // ======================== SETTINGS & ROUTER DNS ========================
  14907. state.settingsSubTab = 'dns';
  14908. state.dnsSettings = null;
  14909. state.dnsStaticRecords = [];
  14910. state.dnsStatus = null;
  14911. function switchSettingsSubTab(sub) {
  14912. state.settingsSubTab = sub;
  14913. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14914. const btnSys = document.getElementById('btn-settings-subtab-system');
  14915. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14916. const tabDns = document.getElementById('settings-subtab-dns');
  14917. const tabSys = document.getElementById('settings-subtab-system');
  14918. const tabBak = document.getElementById('settings-subtab-backup');
  14919. 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';
  14920. 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';
  14921. if (btnDns) btnDns.className = inactiveClass;
  14922. if (btnSys) btnSys.className = inactiveClass;
  14923. if (btnBak) btnBak.className = inactiveClass;
  14924. tabDns?.classList.add('hidden');
  14925. tabSys?.classList.add('hidden');
  14926. tabBak?.classList.add('hidden');
  14927. if (sub === 'dns') {
  14928. if (btnDns) btnDns.className = activeClass;
  14929. tabDns?.classList.remove('hidden');
  14930. loadDNSSettings();
  14931. } else if (sub === 'system') {
  14932. if (btnSys) btnSys.className = activeClass;
  14933. tabSys?.classList.remove('hidden');
  14934. loadSystemSettings();
  14935. } else if (sub === 'backup') {
  14936. if (btnBak) btnBak.className = activeClass;
  14937. tabBak?.classList.remove('hidden');
  14938. loadBackupList();
  14939. }
  14940. }
  14941. async function loadSettingsData(showLoading = false) {
  14942. if (state.settingsSubTab === 'system') {
  14943. await loadSystemSettings();
  14944. } else if (state.settingsSubTab === 'backup') {
  14945. await loadBackupList();
  14946. } else {
  14947. await loadDNSSettings();
  14948. }
  14949. }
  14950. async function loadDNSSettings() {
  14951. try {
  14952. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14953. fetch(`${API_BASE}/dns/settings`),
  14954. fetch(`${API_BASE}/dns/static`),
  14955. fetch(`${API_BASE}/dns/status`)
  14956. ]);
  14957. if (settingsRes.ok) {
  14958. state.dnsSettings = await settingsRes.json();
  14959. populateDNSSettingsForm(state.dnsSettings);
  14960. }
  14961. if (staticRes.ok) {
  14962. state.dnsStaticRecords = await staticRes.json();
  14963. renderStaticDNSList();
  14964. }
  14965. if (statusRes.ok) {
  14966. state.dnsStatus = await statusRes.json();
  14967. updateDNSStatusView(state.dnsStatus);
  14968. }
  14969. } catch (err) {
  14970. console.error('Failed to load DNS settings:', err);
  14971. }
  14972. }
  14973. function populateDNSSettingsForm(s) {
  14974. if (!s) return;
  14975. const dnsForm = document.getElementById('form-dns-settings');
  14976. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14977. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14978. if (dynamicEl) {
  14979. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14980. 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(' ');
  14981. } else {
  14982. dynamicEl.innerText = 'None';
  14983. }
  14984. }
  14985. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14986. if (isEditing) return;
  14987. const serversInput = document.getElementById('dns-servers-input');
  14988. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14989. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14990. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14991. const domainInput = document.getElementById('dns-domain-input');
  14992. if (domainInput) domainInput.value = s.domain || '';
  14993. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14994. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14995. }
  14996. function updateDNSStatusView(st) {
  14997. if (!st) return;
  14998. const preview = document.getElementById('dns-resolv-preview');
  14999. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15000. const pillText = document.getElementById('dns-live-status-text');
  15001. const pill = document.getElementById('dns-live-status-pill');
  15002. if (pill && pillText) {
  15003. if (st.service_running) {
  15004. 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';
  15005. pillText.innerText = 'DNS Service Active';
  15006. } else {
  15007. 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';
  15008. pillText.innerText = 'DNS Service Inactive';
  15009. }
  15010. }
  15011. }
  15012. function appendDNSPreset(preset) {
  15013. const input = document.getElementById('dns-servers-input');
  15014. if (!input) return;
  15015. const dnsForm = document.getElementById('form-dns-settings');
  15016. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15017. const current = input.value.trim();
  15018. if (!current) {
  15019. input.value = preset;
  15020. } else {
  15021. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15022. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15023. toAdd.forEach(ip => {
  15024. if (!existing.includes(ip)) existing.push(ip);
  15025. });
  15026. input.value = existing.join(', ');
  15027. }
  15028. }
  15029. async function saveDNSSettings(e) {
  15030. e.preventDefault();
  15031. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15032. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15033. if (servers.length === 0) {
  15034. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15035. return;
  15036. }
  15037. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15038. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15039. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15040. try {
  15041. const res = await fetch(`${API_BASE}/dns/settings`, {
  15042. method: 'POST',
  15043. headers: { 'Content-Type': 'application/json' },
  15044. body: JSON.stringify({
  15045. servers: servers,
  15046. cache_size: cacheSize,
  15047. domain: domain,
  15048. allow_remote_requests: allowRemote
  15049. })
  15050. });
  15051. const data = await res.json();
  15052. if (res.ok) {
  15053. const dnsForm = document.getElementById('form-dns-settings');
  15054. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15055. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15056. loadDNSSettings();
  15057. } else {
  15058. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15059. }
  15060. } catch (err) {
  15061. showToast('Error', err.message, 'error');
  15062. }
  15063. }
  15064. async function flushDNSCache() {
  15065. try {
  15066. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15067. if (res.ok) {
  15068. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15069. loadDNSSettings();
  15070. } else {
  15071. const err = await res.json();
  15072. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15073. }
  15074. } catch (err) {
  15075. showToast('Error', err.message, 'error');
  15076. }
  15077. }
  15078. function renderStaticDNSList() {
  15079. const tbody = document.getElementById('dns-static-tbody');
  15080. const empty = document.getElementById('dns-static-empty');
  15081. const badge = document.getElementById('dns-static-count-badge');
  15082. if (!tbody) return;
  15083. tbody.innerHTML = '';
  15084. const records = state.dnsStaticRecords || [];
  15085. if (badge) badge.innerText = `${records.length} Records`;
  15086. if (records.length === 0) {
  15087. empty?.classList.remove('hidden');
  15088. return;
  15089. }
  15090. empty?.classList.add('hidden');
  15091. records.forEach(rec => {
  15092. const tr = document.createElement('tr');
  15093. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15094. tr.innerHTML = `
  15095. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15096. <td class="py-2.5 px-4">
  15097. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15098. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15099. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15100. }">
  15101. ${rec.type || 'A'}
  15102. </span>
  15103. </td>
  15104. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15105. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15106. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15107. <td class="py-2.5 px-4">
  15108. <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'}">
  15109. ${rec.disabled ? 'Disabled' : 'Active'}
  15110. </span>
  15111. </td>
  15112. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15113. <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>
  15114. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15115. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15116. </td>
  15117. `;
  15118. tbody.appendChild(tr);
  15119. });
  15120. }
  15121. function openStaticDNSModal(id = null) {
  15122. const modal = document.getElementById('modal-static-dns');
  15123. const title = document.getElementById('modal-static-dns-title');
  15124. const form = document.getElementById('form-static-dns');
  15125. if (!modal || !form) return;
  15126. form.reset();
  15127. document.getElementById('modal-static-dns-id').value = '';
  15128. if (id) {
  15129. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15130. if (rec) {
  15131. if (title) title.innerText = 'Edit Static DNS Record';
  15132. document.getElementById('modal-static-dns-id').value = rec.id;
  15133. document.getElementById('modal-static-dns-name').value = rec.name;
  15134. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15135. document.getElementById('modal-static-dns-addr').value = rec.address;
  15136. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15137. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15138. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15139. }
  15140. } else {
  15141. if (title) title.innerText = 'Add Static DNS Record';
  15142. }
  15143. modal.classList.remove('hidden');
  15144. }
  15145. function closeStaticDNSModal() {
  15146. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15147. }
  15148. async function submitSaveStaticDNS(e) {
  15149. e.preventDefault();
  15150. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15151. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15152. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15153. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15154. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15155. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15156. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15157. if (!name || !address) {
  15158. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15159. return;
  15160. }
  15161. try {
  15162. const res = await fetch(`${API_BASE}/dns/static`, {
  15163. method: 'POST',
  15164. headers: { 'Content-Type': 'application/json' },
  15165. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15166. });
  15167. const data = await res.json();
  15168. if (res.ok) {
  15169. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15170. closeStaticDNSModal();
  15171. loadDNSSettings();
  15172. } else {
  15173. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15174. }
  15175. } catch (err) {
  15176. showToast('Error', err.message, 'error');
  15177. }
  15178. }
  15179. async function deleteStaticDNS(id) {
  15180. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15181. try {
  15182. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15183. if (res.ok) {
  15184. showToast('Deleted', 'Static DNS record deleted', 'success');
  15185. loadDNSSettings();
  15186. }
  15187. } catch (err) {
  15188. showToast('Error', err.message, 'error');
  15189. }
  15190. }
  15191. async function toggleStaticDNS(id, disabled) {
  15192. try {
  15193. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15194. method: 'POST',
  15195. headers: { 'Content-Type': 'application/json' },
  15196. body: JSON.stringify({ disabled })
  15197. });
  15198. if (res.ok) {
  15199. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15200. loadDNSSettings();
  15201. }
  15202. } catch (err) {
  15203. showToast('Error', err.message, 'error');
  15204. }
  15205. }
  15206. async function loadSystemSettings() {
  15207. try {
  15208. const sysForm = document.getElementById('form-system-settings');
  15209. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15210. const res = await fetch(`${API_BASE}/system/settings`);
  15211. if (res.ok) {
  15212. const data = await res.json();
  15213. if (!isEditing) {
  15214. const hostInput = document.getElementById('system-hostname-input');
  15215. if (hostInput) hostInput.value = data.hostname || '';
  15216. const tzInput = document.getElementById('system-timezone-input');
  15217. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15218. }
  15219. }
  15220. } catch (err) {
  15221. console.error('Failed to load system settings:', err);
  15222. }
  15223. }
  15224. async function saveSystemSettings(e) {
  15225. e.preventDefault();
  15226. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15227. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15228. try {
  15229. const res = await fetch(`${API_BASE}/system/settings`, {
  15230. method: 'POST',
  15231. headers: { 'Content-Type': 'application/json' },
  15232. body: JSON.stringify({ hostname, timezone })
  15233. });
  15234. const data = await res.json();
  15235. if (res.ok) {
  15236. const sysForm = document.getElementById('form-system-settings');
  15237. if (sysForm) sysForm.dataset.dirty = 'false';
  15238. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15239. const sideH = document.getElementById('side-hostname');
  15240. if (sideH) sideH.innerText = data.hostname;
  15241. } else {
  15242. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15243. }
  15244. } catch (err) {
  15245. showToast('Error', err.message, 'error');
  15246. }
  15247. }
  15248. // =============================================================================
  15249. // BACKUP & RESTORE MANAGER
  15250. // =============================================================================
  15251. state.selectedBackupFile = null;
  15252. state.inspectedBackupManifest = null;
  15253. state.pendingRestoreTarget = null;
  15254. state.backupsList = [];
  15255. async function exportBackupDownload() {
  15256. const btn = document.getElementById('btn-export-backup');
  15257. const commentInput = document.getElementById('backup-export-comment');
  15258. const comment = (commentInput?.value || '').trim();
  15259. const originalHtml = btn ? btn.innerHTML : '';
  15260. if (btn) {
  15261. btn.disabled = true;
  15262. 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...`;
  15263. }
  15264. try {
  15265. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15266. if (!res.ok) {
  15267. const err = await res.json().catch(() => ({}));
  15268. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15269. return;
  15270. }
  15271. const blob = await res.blob();
  15272. const disposition = res.headers.get('Content-Disposition') || '';
  15273. let filename = 'debtik-backup.zip';
  15274. const match = disposition.match(/filename="?([^";]+)"?/);
  15275. if (match && match[1]) {
  15276. filename = match[1];
  15277. }
  15278. const blobUrl = window.URL.createObjectURL(blob);
  15279. const a = document.createElement('a');
  15280. a.href = blobUrl;
  15281. a.download = filename;
  15282. document.body.appendChild(a);
  15283. a.click();
  15284. setTimeout(() => {
  15285. window.URL.revokeObjectURL(blobUrl);
  15286. a.remove();
  15287. }, 1000);
  15288. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15289. } catch (err) {
  15290. showToast('Export Error', err.message || 'Network error during download', 'error');
  15291. } finally {
  15292. if (btn) {
  15293. btn.disabled = false;
  15294. btn.innerHTML = originalHtml;
  15295. }
  15296. }
  15297. }
  15298. async function onBackupFileSelected(e) {
  15299. const file = e.target.files?.[0];
  15300. if (!file) return;
  15301. const label = document.getElementById('backup-file-label');
  15302. if (label) {
  15303. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15304. }
  15305. await inspectBackupFile(file);
  15306. }
  15307. async function inspectBackupFile(file) {
  15308. const preview = document.getElementById('backup-inspect-preview');
  15309. const restoreBtn = document.getElementById('btn-restore-backup');
  15310. const formData = new FormData();
  15311. formData.append('backup', file);
  15312. try {
  15313. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15314. method: 'POST',
  15315. body: formData
  15316. });
  15317. const data = await res.json();
  15318. if (!res.ok || !data.success || !data.manifest) {
  15319. if (preview) preview.classList.add('hidden');
  15320. if (restoreBtn) restoreBtn.disabled = true;
  15321. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15322. return;
  15323. }
  15324. const mf = data.manifest;
  15325. state.selectedBackupFile = file;
  15326. state.inspectedBackupManifest = mf;
  15327. const vEl = document.getElementById('backup-inspect-version');
  15328. const hEl = document.getElementById('backup-inspect-hostname');
  15329. const fEl = document.getElementById('backup-inspect-files');
  15330. const dEl = document.getElementById('backup-inspect-date');
  15331. const cEl = document.getElementById('backup-inspect-comment');
  15332. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15333. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15334. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15335. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15336. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15337. if (preview) preview.classList.remove('hidden');
  15338. if (restoreBtn) restoreBtn.disabled = false;
  15339. } catch (err) {
  15340. if (preview) preview.classList.add('hidden');
  15341. if (restoreBtn) restoreBtn.disabled = true;
  15342. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15343. }
  15344. }
  15345. function confirmRestoreBackup(localFilename = null) {
  15346. const modal = document.getElementById('modal-restore-confirm');
  15347. const details = document.getElementById('modal-restore-details');
  15348. const progress = document.getElementById('modal-restore-progress');
  15349. const cancelBtn = document.getElementById('btn-cancel-restore');
  15350. const execBtn = document.getElementById('btn-execute-restore');
  15351. if (progress) progress.classList.add('hidden');
  15352. if (cancelBtn) cancelBtn.disabled = false;
  15353. if (execBtn) {
  15354. execBtn.disabled = false;
  15355. execBtn.innerText = 'Yes, Restore & Reload';
  15356. }
  15357. if (localFilename) {
  15358. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15359. if (details) {
  15360. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15361. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15362. }
  15363. } else {
  15364. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15365. showToast('Error', 'Please select a valid backup archive first', 'error');
  15366. return;
  15367. }
  15368. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15369. const mf = state.inspectedBackupManifest;
  15370. if (details) {
  15371. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15372. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15373. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15374. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15375. }
  15376. }
  15377. if (modal) modal.classList.remove('hidden');
  15378. }
  15379. function closeRestoreModal() {
  15380. const modal = document.getElementById('modal-restore-confirm');
  15381. if (modal) modal.classList.add('hidden');
  15382. }
  15383. async function executeRestoreBackup() {
  15384. const target = state.pendingRestoreTarget;
  15385. if (!target) return;
  15386. const progress = document.getElementById('modal-restore-progress');
  15387. const progressText = document.getElementById('modal-restore-progress-text');
  15388. const cancelBtn = document.getElementById('btn-cancel-restore');
  15389. const execBtn = document.getElementById('btn-execute-restore');
  15390. if (cancelBtn) cancelBtn.disabled = true;
  15391. if (execBtn) execBtn.disabled = true;
  15392. if (progress) progress.classList.remove('hidden');
  15393. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15394. try {
  15395. let res;
  15396. if (target.type === 'file') {
  15397. const formData = new FormData();
  15398. formData.append('backup', target.file);
  15399. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15400. method: 'POST',
  15401. body: formData
  15402. });
  15403. } else {
  15404. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15405. method: 'POST'
  15406. });
  15407. }
  15408. const data = await res.json();
  15409. if (!res.ok || !data.success) {
  15410. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15411. if (cancelBtn) cancelBtn.disabled = false;
  15412. if (execBtn) execBtn.disabled = false;
  15413. if (progress) progress.classList.add('hidden');
  15414. return;
  15415. }
  15416. if (progressText) {
  15417. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15418. }
  15419. pollAfterRestoreReconnect();
  15420. } catch (err) {
  15421. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15422. if (cancelBtn) cancelBtn.disabled = false;
  15423. if (execBtn) execBtn.disabled = false;
  15424. if (progress) progress.classList.add('hidden');
  15425. }
  15426. }
  15427. function pollAfterRestoreReconnect() {
  15428. let attempts = 0;
  15429. const maxAttempts = 25;
  15430. const timer = setInterval(async () => {
  15431. attempts++;
  15432. try {
  15433. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15434. if (res.ok) {
  15435. clearInterval(timer);
  15436. closeRestoreModal();
  15437. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15438. setTimeout(() => {
  15439. window.location.reload();
  15440. }, 1200);
  15441. }
  15442. } catch (_) {
  15443. // Still restarting, retry
  15444. }
  15445. if (attempts >= maxAttempts) {
  15446. clearInterval(timer);
  15447. closeRestoreModal();
  15448. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15449. }
  15450. }, 1500);
  15451. }
  15452. async function loadBackupList() {
  15453. const tbody = document.getElementById('backups-table-tbody');
  15454. const empty = document.getElementById('backups-empty-state');
  15455. if (!tbody) return;
  15456. try {
  15457. const res = await fetch(`${API_BASE}/system/backups`);
  15458. if (!res.ok) return;
  15459. const list = await res.json();
  15460. state.backupsList = list || [];
  15461. renderBackupsTable(state.backupsList);
  15462. } catch (err) {
  15463. console.error('Failed to load backup list:', err);
  15464. }
  15465. }
  15466. function renderBackupsTable(backups) {
  15467. const tbody = document.getElementById('backups-table-tbody');
  15468. const empty = document.getElementById('backups-empty-state');
  15469. if (!tbody) return;
  15470. if (!backups || backups.length === 0) {
  15471. tbody.innerHTML = '';
  15472. if (empty) empty.classList.remove('hidden');
  15473. return;
  15474. }
  15475. if (empty) empty.classList.add('hidden');
  15476. tbody.innerHTML = backups.map(bk => {
  15477. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15478. const badge = isAuto
  15479. ? `<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>`
  15480. : `<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>`;
  15481. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15482. return `<tr class="hover:bg-slate-800/40 transition">
  15483. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15484. ${badge}
  15485. <span>${escapeHtml(bk.filename)}</span>
  15486. </td>
  15487. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15488. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15489. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15490. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15491. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15492. <td class="py-3 px-4 text-right space-x-2">
  15493. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15494. 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">
  15495. Download
  15496. </button>
  15497. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15498. 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">
  15499. Restore
  15500. </button>
  15501. </td>
  15502. </tr>`;
  15503. }).join('');
  15504. }
  15505. async function downloadLocalBackup(filename) {
  15506. try {
  15507. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15508. if (!res.ok) {
  15509. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15510. return;
  15511. }
  15512. const blob = await res.blob();
  15513. const blobUrl = window.URL.createObjectURL(blob);
  15514. const a = document.createElement('a');
  15515. a.href = blobUrl;
  15516. a.download = filename;
  15517. document.body.appendChild(a);
  15518. a.click();
  15519. setTimeout(() => {
  15520. window.URL.revokeObjectURL(blobUrl);
  15521. a.remove();
  15522. }, 1000);
  15523. } catch (err) {
  15524. showToast('Download Error', err.message, 'error');
  15525. }
  15526. }
  15527. // =============================================================================
  15528. // AUTHENTICATION & USER MANAGER
  15529. // =============================================================================
  15530. async function checkAuthStatus() {
  15531. try {
  15532. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15533. headers: {
  15534. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15535. }
  15536. });
  15537. if (res.ok) {
  15538. const user = await res.json();
  15539. state.currentUser = user;
  15540. updateUserProfileHeader(user);
  15541. hideLoginScreen();
  15542. state.isPolling = true;
  15543. fetchData();
  15544. initLiveTrafficStream();
  15545. return true;
  15546. } else {
  15547. showLoginScreen(false);
  15548. return false;
  15549. }
  15550. } catch (err) {
  15551. showLoginScreen(false);
  15552. return false;
  15553. }
  15554. }
  15555. function showLoginScreen(isExpired = false) {
  15556. const el = document.getElementById('login-screen');
  15557. if (el) el.classList.remove('hidden');
  15558. const errEl = document.getElementById('login-error');
  15559. const errTxt = document.getElementById('login-error-text');
  15560. if (isExpired && errEl && errTxt) {
  15561. errTxt.innerText = 'Session expired. Please sign in again.';
  15562. errEl.classList.remove('hidden');
  15563. } else if (errEl) {
  15564. errEl.classList.add('hidden');
  15565. }
  15566. const pwInput = document.getElementById('login-password');
  15567. if (pwInput) pwInput.value = '';
  15568. const userInput = document.getElementById('login-username');
  15569. if (userInput && !userInput.value) userInput.focus();
  15570. else if (pwInput) pwInput.focus();
  15571. }
  15572. function hideLoginScreen() {
  15573. const el = document.getElementById('login-screen');
  15574. if (el) el.classList.add('hidden');
  15575. const errEl = document.getElementById('login-error');
  15576. if (errEl) errEl.classList.add('hidden');
  15577. }
  15578. async function handleLoginSubmit(event) {
  15579. event.preventDefault();
  15580. const username = (document.getElementById('login-username')?.value || '').trim();
  15581. const password = document.getElementById('login-password')?.value || '';
  15582. const errEl = document.getElementById('login-error');
  15583. const errTxt = document.getElementById('login-error-text');
  15584. const btn = document.getElementById('login-submit-btn');
  15585. const btnText = document.getElementById('login-btn-text');
  15586. const spinner = document.getElementById('login-btn-spinner');
  15587. if (!username || !password) {
  15588. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15589. if (errEl) errEl.classList.remove('hidden');
  15590. return;
  15591. }
  15592. if (errEl) errEl.classList.add('hidden');
  15593. if (btn) btn.disabled = true;
  15594. if (btnText) btnText.innerText = 'Authenticating...';
  15595. if (spinner) spinner.classList.remove('hidden');
  15596. try {
  15597. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15598. method: 'POST',
  15599. headers: { 'Content-Type': 'application/json' },
  15600. body: JSON.stringify({ username, password })
  15601. });
  15602. const data = await res.json();
  15603. if (res.ok && data.success) {
  15604. localStorage.setItem('debtik_token', data.token);
  15605. state.currentUser = data.user;
  15606. updateUserProfileHeader(data.user);
  15607. hideLoginScreen();
  15608. state.isPolling = true;
  15609. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15610. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15611. navigate(hash);
  15612. fetchData();
  15613. initLiveTrafficStream();
  15614. // Ensure background telemetry polling is active
  15615. if (!window._telemetryInterval) {
  15616. window._telemetryInterval = setInterval(() => {
  15617. if (state.isPolling && state.currentUser && !document.hidden) {
  15618. fetchData(false);
  15619. }
  15620. }, 5000);
  15621. }
  15622. } else {
  15623. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15624. if (errEl) errEl.classList.remove('hidden');
  15625. }
  15626. } catch (err) {
  15627. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15628. if (errEl) errEl.classList.remove('hidden');
  15629. } finally {
  15630. if (btn) btn.disabled = false;
  15631. if (btnText) btnText.innerText = 'Sign In to Controller';
  15632. if (spinner) spinner.classList.add('hidden');
  15633. }
  15634. }
  15635. async function handleLogoutClick() {
  15636. try {
  15637. await originalFetch(`${API_BASE}/auth/logout`, {
  15638. method: 'POST',
  15639. headers: {
  15640. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15641. }
  15642. });
  15643. } catch (e) {}
  15644. stopSessionPolling();
  15645. localStorage.removeItem('debtik_token');
  15646. state.currentUser = null;
  15647. state.isPolling = false;
  15648. if (window._telemetryInterval) {
  15649. clearInterval(window._telemetryInterval);
  15650. window._telemetryInterval = null;
  15651. }
  15652. if (trafficEventSource) {
  15653. trafficEventSource.close();
  15654. trafficEventSource = null;
  15655. }
  15656. if (trafficPollFallback) {
  15657. clearInterval(trafficPollFallback);
  15658. trafficPollFallback = null;
  15659. }
  15660. showLoginScreen(false);
  15661. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15662. }
  15663. function togglePasswordVisibility(id) {
  15664. const input = document.getElementById(id);
  15665. if (!input) return;
  15666. input.type = input.type === 'password' ? 'text' : 'password';
  15667. }
  15668. function toggleUserMenu() {
  15669. const menu = document.getElementById('user-menu-dropdown');
  15670. if (menu) menu.classList.toggle('hidden');
  15671. }
  15672. function closeUserMenu() {
  15673. const menu = document.getElementById('user-menu-dropdown');
  15674. if (menu) menu.classList.add('hidden');
  15675. }
  15676. // Close user menu on outside click
  15677. document.addEventListener('click', (e) => {
  15678. const menu = document.getElementById('user-menu-dropdown');
  15679. if (!menu || menu.classList.contains('hidden')) return;
  15680. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15681. menu.classList.add('hidden');
  15682. }
  15683. });
  15684. function updateUserProfileHeader(user) {
  15685. if (!user) return;
  15686. const navName = document.getElementById('nav-user-name');
  15687. if (navName) navName.innerText = user.username;
  15688. const dropName = document.getElementById('dropdown-user-name');
  15689. if (dropName) dropName.innerText = user.username;
  15690. const navRole = document.getElementById('nav-user-role');
  15691. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15692. const navAvatar = document.getElementById('nav-user-avatar');
  15693. if (navAvatar) {
  15694. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15695. navAvatar.innerText = initials;
  15696. }
  15697. const statCurUser = document.getElementById('stat-current-user');
  15698. if (statCurUser) statCurUser.innerText = user.username;
  15699. const statCurRole = document.getElementById('stat-current-role');
  15700. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15701. // Role permissions UI visibility: hide user management for non-admins
  15702. const isFullAdmin = user.role === 'full';
  15703. const navUsers = document.getElementById('nav-users');
  15704. if (navUsers) {
  15705. if (isFullAdmin) navUsers.classList.remove('hidden');
  15706. else navUsers.classList.add('hidden');
  15707. }
  15708. const dropdownUsers = document.getElementById('dropdown-item-users');
  15709. if (dropdownUsers) {
  15710. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15711. else dropdownUsers.classList.add('hidden');
  15712. }
  15713. }
  15714. // ================= User Management CRUD =================
  15715. async function loadUsers(isManual = false) {
  15716. try {
  15717. const res = await fetch(`${API_BASE}/users`);
  15718. if (res.status === 403) {
  15719. const tbody = document.getElementById('users-table-tbody');
  15720. if (tbody) {
  15721. tbody.innerHTML = `
  15722. <tr>
  15723. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15724. <div class="inline-flex items-center gap-2">
  15725. <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>
  15726. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15727. </div>
  15728. </td>
  15729. </tr>
  15730. `;
  15731. }
  15732. return;
  15733. }
  15734. if (res.ok) {
  15735. state.users = await res.json();
  15736. renderUsersTable();
  15737. const totalUsers = document.getElementById('stat-total-users');
  15738. if (totalUsers) totalUsers.innerText = state.users.length;
  15739. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15740. const adminUsers = document.getElementById('stat-admin-users');
  15741. if (adminUsers) adminUsers.innerText = adminCount;
  15742. const badgeCount = document.getElementById('badge-users-count');
  15743. if (badgeCount) badgeCount.innerText = state.users.length;
  15744. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15745. }
  15746. } catch (err) {
  15747. console.error('Failed to load users:', err);
  15748. }
  15749. }
  15750. function renderUsersTable() {
  15751. const tbody = document.getElementById('users-table-tbody');
  15752. const emptyState = document.getElementById('users-empty-state');
  15753. if (!tbody) return;
  15754. tbody.innerHTML = '';
  15755. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15756. const filtered = (state.users || []).filter(u => {
  15757. if (!query) return true;
  15758. return u.username.toLowerCase().includes(query) ||
  15759. (u.role || '').toLowerCase().includes(query) ||
  15760. (u.comment || '').toLowerCase().includes(query);
  15761. });
  15762. if (filtered.length === 0) {
  15763. if (emptyState) emptyState.classList.remove('hidden');
  15764. return;
  15765. }
  15766. if (emptyState) emptyState.classList.add('hidden');
  15767. const currentAuthUser = state.currentUser?.username || '';
  15768. filtered.forEach(u => {
  15769. const isSelf = u.username === currentAuthUser;
  15770. const isFull = u.role === 'full';
  15771. const isWrite = u.role === 'write';
  15772. 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>`;
  15773. if (isFull) {
  15774. 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>`;
  15775. } else if (isWrite) {
  15776. 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>`;
  15777. }
  15778. const statusBadge = u.disabled
  15779. ? `<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>`
  15780. : `<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>`;
  15781. let lastLoginText = 'Never';
  15782. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15783. const dt = new Date(u.last_login_at);
  15784. lastLoginText = dt.toLocaleString();
  15785. }
  15786. const initials = u.username.slice(0, 2).toUpperCase();
  15787. const tr = document.createElement('tr');
  15788. tr.className = 'hover:bg-slate-800/40 transition group';
  15789. tr.innerHTML = `
  15790. <td class="py-3 px-4">
  15791. <div class="flex items-center gap-3">
  15792. <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">
  15793. ${initials}
  15794. </div>
  15795. <div>
  15796. <div class="font-bold text-white text-xs flex items-center gap-2">
  15797. <span>${escapeHtml(u.username)}</span>
  15798. ${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>' : ''}
  15799. </div>
  15800. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15801. </div>
  15802. </div>
  15803. </td>
  15804. <td class="py-3 px-4 font-sans">
  15805. ${roleBadge}
  15806. </td>
  15807. <td class="py-3 px-4 font-sans">
  15808. ${statusBadge}
  15809. </td>
  15810. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15811. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15812. </td>
  15813. <td class="py-3 px-4 text-slate-400 text-xs">
  15814. ${lastLoginText}
  15815. </td>
  15816. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15817. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15818. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15819. <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>
  15820. </button>
  15821. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15822. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15823. <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>
  15824. </button>
  15825. ${!isSelf ? `
  15826. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15827. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15828. <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>
  15829. </button>
  15830. ` : ''}
  15831. </td>
  15832. `;
  15833. tbody.appendChild(tr);
  15834. });
  15835. }
  15836. function openAddUserModal() {
  15837. document.getElementById('user-add-username').value = '';
  15838. document.getElementById('user-add-password').value = '';
  15839. document.getElementById('user-add-confirm').value = '';
  15840. document.getElementById('user-add-role').value = 'full';
  15841. document.getElementById('user-add-comment').value = '';
  15842. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15843. document.getElementById('user-add-username')?.focus();
  15844. }
  15845. function closeAddUserModal() {
  15846. document.getElementById('modal-add-user')?.classList.add('hidden');
  15847. }
  15848. async function submitAddUser(event) {
  15849. event.preventDefault();
  15850. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15851. const password = document.getElementById('user-add-password')?.value || '';
  15852. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15853. const role = document.getElementById('user-add-role')?.value || 'full';
  15854. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15855. if (password !== confirm) {
  15856. showToast('Validation Error', 'Passwords do not match', 'warning');
  15857. return;
  15858. }
  15859. if (password.length < 4) {
  15860. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15861. return;
  15862. }
  15863. try {
  15864. const res = await fetch(`${API_BASE}/users`, {
  15865. method: 'POST',
  15866. headers: { 'Content-Type': 'application/json' },
  15867. body: JSON.stringify({ username, password, role, comment })
  15868. });
  15869. const data = await res.json();
  15870. if (res.ok) {
  15871. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15872. closeAddUserModal();
  15873. loadUsers(false);
  15874. } else {
  15875. showToast('Error', data.message || 'Failed to create user', 'error');
  15876. }
  15877. } catch (err) {
  15878. showToast('Error', err.message, 'error');
  15879. }
  15880. }
  15881. function openEditUserModal(username) {
  15882. const user = (state.users || []).find(u => u.username === username);
  15883. if (!user) return;
  15884. document.getElementById('user-edit-username').value = user.username;
  15885. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15886. document.getElementById('user-edit-role').value = user.role || 'read';
  15887. document.getElementById('user-edit-comment').value = user.comment || '';
  15888. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15889. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15890. }
  15891. function closeEditUserModal() {
  15892. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15893. }
  15894. async function submitEditUser(event) {
  15895. event.preventDefault();
  15896. const username = document.getElementById('user-edit-username')?.value;
  15897. const role = document.getElementById('user-edit-role')?.value || 'read';
  15898. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15899. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15900. try {
  15901. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15902. method: 'PUT',
  15903. headers: { 'Content-Type': 'application/json' },
  15904. body: JSON.stringify({ role, comment, disabled })
  15905. });
  15906. const data = await res.json();
  15907. if (res.ok) {
  15908. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15909. closeEditUserModal();
  15910. loadUsers(false);
  15911. // If updated own role/disabled status, refresh self profile
  15912. if (username === state.currentUser?.username) {
  15913. checkAuthStatus();
  15914. }
  15915. } else {
  15916. showToast('Error', data.message || 'Failed to update user', 'error');
  15917. }
  15918. } catch (err) {
  15919. showToast('Error', err.message, 'error');
  15920. }
  15921. }
  15922. function openAdminResetPasswordModal(username) {
  15923. document.getElementById('admin-reset-username').value = username;
  15924. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15925. document.getElementById('admin-reset-new-pw').value = '';
  15926. document.getElementById('admin-reset-confirm-pw').value = '';
  15927. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15928. document.getElementById('admin-reset-new-pw')?.focus();
  15929. }
  15930. function closeAdminResetPasswordModal() {
  15931. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15932. }
  15933. async function submitAdminResetPassword(event) {
  15934. event.preventDefault();
  15935. const username = document.getElementById('admin-reset-username')?.value;
  15936. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15937. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15938. if (newPassword !== confirm) {
  15939. showToast('Validation Error', 'Passwords do not match', 'warning');
  15940. return;
  15941. }
  15942. if (newPassword.length < 4) {
  15943. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15944. return;
  15945. }
  15946. try {
  15947. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15948. method: 'POST',
  15949. headers: { 'Content-Type': 'application/json' },
  15950. body: JSON.stringify({ new_password: newPassword })
  15951. });
  15952. const data = await res.json();
  15953. if (res.ok) {
  15954. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15955. closeAdminResetPasswordModal();
  15956. } else {
  15957. showToast('Error', data.message || 'Failed to reset password', 'error');
  15958. }
  15959. } catch (err) {
  15960. showToast('Error', err.message, 'error');
  15961. }
  15962. }
  15963. async function deleteUser(username) {
  15964. if (username === state.currentUser?.username) {
  15965. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15966. return;
  15967. }
  15968. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15969. return;
  15970. }
  15971. try {
  15972. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15973. method: 'DELETE'
  15974. });
  15975. const data = await res.json();
  15976. if (res.ok) {
  15977. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15978. loadUsers(false);
  15979. } else {
  15980. showToast('Error', data.message || 'Failed to delete user', 'error');
  15981. }
  15982. } catch (err) {
  15983. showToast('Error', err.message, 'error');
  15984. }
  15985. }
  15986. function openSelfPasswordModal() {
  15987. document.getElementById('self-current-password').value = '';
  15988. document.getElementById('self-new-password').value = '';
  15989. document.getElementById('self-confirm-password').value = '';
  15990. document.getElementById('modal-self-password')?.classList.remove('hidden');
  15991. document.getElementById('self-current-password')?.focus();
  15992. }
  15993. function closeSelfPasswordModal() {
  15994. document.getElementById('modal-self-password')?.classList.add('hidden');
  15995. }
  15996. async function submitSelfPassword(event) {
  15997. event.preventDefault();
  15998. const oldPassword = document.getElementById('self-current-password')?.value || '';
  15999. const newPassword = document.getElementById('self-new-password')?.value || '';
  16000. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16001. if (newPassword !== confirm) {
  16002. showToast('Validation Error', 'New passwords do not match', 'warning');
  16003. return;
  16004. }
  16005. if (newPassword.length < 4) {
  16006. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16007. return;
  16008. }
  16009. try {
  16010. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16011. method: 'POST',
  16012. headers: { 'Content-Type': 'application/json' },
  16013. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16014. });
  16015. const data = await res.json();
  16016. if (res.ok) {
  16017. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16018. closeSelfPasswordModal();
  16019. } else {
  16020. showToast('Error', data.message || 'Failed to change password', 'error');
  16021. }
  16022. } catch (err) {
  16023. showToast('Error', err.message, 'error');
  16024. }
  16025. }
  16026. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16027. state.services = [];
  16028. async function loadServices(manual = false) {
  16029. try {
  16030. const res = await fetch(`${API_BASE}/system/services`);
  16031. if (!res.ok) throw new Error('Failed to load services');
  16032. const data = await res.json();
  16033. state.services = data || [];
  16034. renderServicesTable();
  16035. updateCertificatesBadges();
  16036. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16037. } catch (err) {
  16038. if (manual) showToast('Error', err.message, 'error');
  16039. }
  16040. }
  16041. function renderServicesTable() {
  16042. const tbody = document.getElementById('services-table-body');
  16043. if (!tbody) return;
  16044. if (!state.services || state.services.length === 0) {
  16045. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16046. return;
  16047. }
  16048. tbody.innerHTML = state.services.map(s => {
  16049. const isOff = s.disabled;
  16050. const statusBadge = isOff
  16051. ? '<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>'
  16052. : '<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>';
  16053. const toggleBtn = isOff
  16054. ? `<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>`
  16055. : `<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>`;
  16056. let certBadge = '';
  16057. if (s.name === 'www-ssl') {
  16058. if (s.certificate) {
  16059. 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>`;
  16060. } else {
  16061. 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>`;
  16062. }
  16063. }
  16064. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16065. return `
  16066. <tr class="hover:bg-slate-800/40 transition">
  16067. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16068. <td class="py-3 px-4">
  16069. <div class="flex items-center gap-2">
  16070. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16071. <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">
  16072. <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>
  16073. </button>
  16074. </div>
  16075. </td>
  16076. <td class="py-3 px-4">${statusBadge}</td>
  16077. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16078. <td class="py-3 px-4 text-right">
  16079. <div class="flex items-center justify-end gap-2">
  16080. <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">
  16081. <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>
  16082. <span>Edit</span>
  16083. </button>
  16084. ${toggleBtn}
  16085. </div>
  16086. </td>
  16087. </tr>
  16088. `;
  16089. }).join('');
  16090. }
  16091. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16092. document.getElementById('modal-service-name').value = serviceName;
  16093. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16094. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16095. document.getElementById('modal-service-port').value = currentPort;
  16096. const hintEl = document.getElementById('modal-service-port-hint');
  16097. const warnEl = document.getElementById('modal-service-warning');
  16098. const certGroup = document.getElementById('modal-service-cert-group');
  16099. const certSelect = document.getElementById('modal-service-cert-select');
  16100. if (serviceName === 'www') {
  16101. hintEl.textContent = 'Default HTTP web port: 80';
  16102. warnEl.classList.remove('hidden');
  16103. certGroup.classList.add('hidden');
  16104. } else if (serviceName === 'www-ssl') {
  16105. hintEl.textContent = 'Default HTTPS web port: 443';
  16106. warnEl.classList.remove('hidden');
  16107. certGroup.classList.remove('hidden');
  16108. const populateCertOptions = (certs) => {
  16109. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16110. (certs || []).forEach(c => {
  16111. const opt = document.createElement('option');
  16112. opt.value = c.name;
  16113. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16114. if (c.name === currentCert) opt.selected = true;
  16115. certSelect.appendChild(opt);
  16116. });
  16117. };
  16118. if (state.certificates && state.certificates.length > 0) {
  16119. populateCertOptions(state.certificates);
  16120. } else {
  16121. loadCertificates(false).then(() => {
  16122. populateCertOptions(state.certificates);
  16123. });
  16124. }
  16125. } else if (serviceName === 'telnet') {
  16126. hintEl.textContent = 'Default Telnet console port: 8282';
  16127. warnEl.classList.add('hidden');
  16128. certGroup.classList.add('hidden');
  16129. } else if (serviceName === 'ssh') {
  16130. hintEl.textContent = 'Default SSH port: 2222';
  16131. warnEl.classList.add('hidden');
  16132. certGroup.classList.add('hidden');
  16133. } else {
  16134. hintEl.textContent = '';
  16135. warnEl.classList.add('hidden');
  16136. certGroup.classList.add('hidden');
  16137. }
  16138. const modal = document.getElementById('modal-service-edit');
  16139. modal.classList.remove('hidden');
  16140. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16141. }
  16142. function closeEditServiceModal() {
  16143. const modal = document.getElementById('modal-service-edit');
  16144. if (modal) modal.classList.add('hidden');
  16145. }
  16146. async function submitSaveServicePort(event) {
  16147. event.preventDefault();
  16148. const name = document.getElementById('modal-service-name').value;
  16149. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16150. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16151. if (isNaN(port) || port < 1 || port > 65535) {
  16152. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16153. return;
  16154. }
  16155. const certSelect = document.getElementById('modal-service-cert-select');
  16156. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16157. try {
  16158. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16159. method: 'POST',
  16160. headers: { 'Content-Type': 'application/json' },
  16161. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16162. });
  16163. if (!res.ok) {
  16164. const errData = await res.json();
  16165. throw new Error(errData.message || 'Failed to update service settings');
  16166. }
  16167. closeEditServiceModal();
  16168. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16169. await loadServices();
  16170. } catch (err) {
  16171. showToast('Error', err.message, 'error');
  16172. }
  16173. }
  16174. async function toggleServiceState(serviceName, newDisabled) {
  16175. if (serviceName === 'www' && newDisabled) {
  16176. 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?")) {
  16177. return;
  16178. }
  16179. }
  16180. if (serviceName === 'www-ssl' && !newDisabled) {
  16181. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16182. if (!sslSvc || !sslSvc.certificate) {
  16183. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16184. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16185. return;
  16186. }
  16187. }
  16188. try {
  16189. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16190. method: 'POST',
  16191. headers: { 'Content-Type': 'application/json' },
  16192. body: JSON.stringify({ disabled: newDisabled })
  16193. });
  16194. if (!res.ok) {
  16195. const errData = await res.json();
  16196. throw new Error(errData.message || 'Failed to update service');
  16197. }
  16198. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16199. await loadServices();
  16200. } catch (err) {
  16201. showToast('Error', err.message, 'error');
  16202. }
  16203. }
  16204. // ==================== SYSTEM LOGS (/log) ====================
  16205. state.logs = [];
  16206. let logsTimer = null;
  16207. async function loadLogs(manual = false) {
  16208. const limitEl = document.getElementById('logs-limit-select');
  16209. const limit = limitEl ? limitEl.value : '100';
  16210. try {
  16211. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16212. if (!res.ok) throw new Error('Failed to load logs');
  16213. const data = await res.json();
  16214. state.logs = data.logs || [];
  16215. renderLogsTable();
  16216. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16217. } catch (err) {
  16218. if (manual) showToast('Error', err.message, 'error');
  16219. }
  16220. // Setup auto-refresh if enabled and on logs tab
  16221. if (!logsTimer && state.currentUser) {
  16222. logsTimer = setInterval(() => {
  16223. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16224. const auto = document.getElementById('logs-auto-refresh');
  16225. if (auto && auto.checked) {
  16226. loadLogs(false);
  16227. }
  16228. }
  16229. }, 3000);
  16230. }
  16231. }
  16232. function renderLogsTable() {
  16233. const tbody = document.getElementById('logs-table-body');
  16234. if (!tbody) return;
  16235. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16236. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16237. const filtered = state.logs.filter(entry => {
  16238. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16239. return false;
  16240. }
  16241. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16242. return false;
  16243. }
  16244. return true;
  16245. });
  16246. if (filtered.length === 0) {
  16247. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16248. return;
  16249. }
  16250. tbody.innerHTML = filtered.map(l => {
  16251. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16252. const topLower = l.topics.toLowerCase();
  16253. if (topLower.includes('auth')) {
  16254. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16255. } else if (topLower.includes('dhcp')) {
  16256. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16257. } else if (topLower.includes('route')) {
  16258. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16259. } else if (topLower.includes('firewall')) {
  16260. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16261. } else if (topLower.includes('error')) {
  16262. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16263. } else if (topLower.includes('system')) {
  16264. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16265. }
  16266. const d = new Date(l.time);
  16267. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16268. return `
  16269. <tr class="hover:bg-slate-800/40 transition">
  16270. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16271. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16272. <td class="py-2 px-3 whitespace-nowrap">
  16273. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16274. </td>
  16275. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16276. </tr>
  16277. `;
  16278. }).join('');
  16279. }
  16280. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16281. state.certificates = [];
  16282. async function loadCertificates(manual = false) {
  16283. try {
  16284. const res = await fetch(`${API_BASE}/certificates`);
  16285. if (!res.ok) throw new Error('Failed to load certificates');
  16286. state.certificates = await res.json() || [];
  16287. updateCertificatesBadges();
  16288. renderCertificatesTable();
  16289. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16290. } catch (err) {
  16291. if (manual) showToast('Error', err.message, 'error');
  16292. }
  16293. }
  16294. function updateCertificatesBadges() {
  16295. const total = (state.certificates || []).length;
  16296. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16297. const bCount = document.getElementById('badge-certs-count');
  16298. if (bCount) bCount.innerText = total;
  16299. const kpiTotal = document.getElementById('kpi-certs-total');
  16300. if (kpiTotal) kpiTotal.innerText = total;
  16301. const kpiCA = document.getElementById('kpi-certs-ca');
  16302. if (kpiCA) kpiCA.innerText = caCount;
  16303. const kpiHttps = document.getElementById('kpi-https-status');
  16304. if (kpiHttps) {
  16305. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16306. if (sslSvc) {
  16307. if (!sslSvc.disabled) {
  16308. 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>`;
  16309. } else {
  16310. 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>`;
  16311. }
  16312. }
  16313. }
  16314. }
  16315. function renderCertificatesTable() {
  16316. const tbody = document.getElementById('certs-table-body');
  16317. if (!tbody) return;
  16318. if (!state.certificates || state.certificates.length === 0) {
  16319. 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>';
  16320. return;
  16321. }
  16322. tbody.innerHTML = state.certificates.map(c => {
  16323. let typeBadge = '';
  16324. if (c.is_ca) {
  16325. 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>';
  16326. } else if (c.type === 'acme') {
  16327. 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>';
  16328. } else if (c.issuer && c.issuer !== c.common_name) {
  16329. 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>';
  16330. } else {
  16331. 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>';
  16332. }
  16333. const sansHtml = (c.sans && c.sans.length > 0)
  16334. ? 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('')
  16335. : '<span class="text-slate-500">-</span>';
  16336. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16337. let validStr = '-';
  16338. let validBadge = '';
  16339. if (validTo && !isNaN(validTo.getTime())) {
  16340. const now = new Date();
  16341. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16342. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16343. if (daysLeft < 0) {
  16344. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16345. } else if (daysLeft < 30) {
  16346. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16347. } else {
  16348. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16349. }
  16350. }
  16351. return `
  16352. <tr class="hover:bg-slate-800/40 transition">
  16353. <td class="py-3 px-4">${typeBadge}</td>
  16354. <td class="py-3 px-4">
  16355. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16356. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16357. </td>
  16358. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16359. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16360. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16361. <span>${validStr}</span> ${validBadge}
  16362. ${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>` : ''}
  16363. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16364. </td>
  16365. <td class="py-3 px-4 text-right whitespace-nowrap">
  16366. <div class="flex items-center justify-end gap-1.5">
  16367. <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">
  16368. <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>
  16369. <span>View</span>
  16370. </button>
  16371. <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">
  16372. <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>
  16373. </button>
  16374. </div>
  16375. </td>
  16376. </tr>
  16377. `;
  16378. }).join('');
  16379. }
  16380. // Create CA
  16381. function openCreateCAModal() {
  16382. document.getElementById('form-create-ca').reset();
  16383. document.getElementById('ca-days').value = '3650';
  16384. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16385. document.getElementById('ca-country').value = 'GR';
  16386. document.getElementById('ca-key-type').value = 'RSA-2048';
  16387. document.getElementById('modal-create-ca').classList.remove('hidden');
  16388. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16389. }
  16390. function closeCreateCAModal() {
  16391. document.getElementById('modal-create-ca').classList.add('hidden');
  16392. }
  16393. async function submitCreateCA(event) {
  16394. event.preventDefault();
  16395. const payload = {
  16396. name: document.getElementById('ca-name').value.trim(),
  16397. common_name: document.getElementById('ca-cn').value.trim(),
  16398. organization: document.getElementById('ca-org').value.trim(),
  16399. country: document.getElementById('ca-country').value.trim(),
  16400. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16401. key_type: document.getElementById('ca-key-type').value
  16402. };
  16403. try {
  16404. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16405. method: 'POST',
  16406. headers: { 'Content-Type': 'application/json' },
  16407. body: JSON.stringify(payload)
  16408. });
  16409. if (!res.ok) {
  16410. const errData = await res.json();
  16411. throw new Error(errData.message || 'Failed to create CA');
  16412. }
  16413. closeCreateCAModal();
  16414. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16415. await loadCertificates();
  16416. } catch (err) {
  16417. showToast('Error', err.message, 'error');
  16418. }
  16419. }
  16420. // Create Cert
  16421. function openCreateCertModal() {
  16422. document.getElementById('form-create-cert').reset();
  16423. document.getElementById('cert-days').value = '730';
  16424. document.getElementById('cert-key-type').value = 'RSA-2048';
  16425. const caSelect = document.getElementById('cert-ca-select');
  16426. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16427. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16428. const opt = document.createElement('option');
  16429. opt.value = ca.name;
  16430. opt.textContent = `${ca.name} (${ca.common_name})`;
  16431. caSelect.appendChild(opt);
  16432. });
  16433. document.getElementById('modal-create-cert').classList.remove('hidden');
  16434. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16435. }
  16436. function closeCreateCertModal() {
  16437. document.getElementById('modal-create-cert').classList.add('hidden');
  16438. }
  16439. async function submitCreateCert(event) {
  16440. event.preventDefault();
  16441. const rawSans = document.getElementById('cert-sans').value;
  16442. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16443. const caName = document.getElementById('cert-ca-select').value;
  16444. const payload = {
  16445. name: document.getElementById('cert-name').value.trim(),
  16446. common_name: document.getElementById('cert-cn').value.trim(),
  16447. ca_name: caName,
  16448. sans: sansList,
  16449. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16450. key_type: document.getElementById('cert-key-type').value,
  16451. is_server: true
  16452. };
  16453. try {
  16454. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16455. method: 'POST',
  16456. headers: { 'Content-Type': 'application/json' },
  16457. body: JSON.stringify(payload)
  16458. });
  16459. if (!res.ok) {
  16460. const errData = await res.json();
  16461. throw new Error(errData.message || 'Failed to issue certificate');
  16462. }
  16463. closeCreateCertModal();
  16464. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16465. await loadCertificates();
  16466. } catch (err) {
  16467. showToast('Error', err.message, 'error');
  16468. }
  16469. }
  16470. // Let's Encrypt
  16471. function openLetsEncryptModal() {
  16472. document.getElementById('form-letsencrypt').reset();
  16473. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16474. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16475. }
  16476. function closeLetsEncryptModal() {
  16477. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16478. }
  16479. async function submitLetsEncrypt(event) {
  16480. event.preventDefault();
  16481. const domain = document.getElementById('le-domain').value.trim();
  16482. const email = document.getElementById('le-email').value.trim();
  16483. let name = document.getElementById('le-name').value.trim();
  16484. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16485. const staging = document.getElementById('le-staging').checked;
  16486. const btn = document.getElementById('btn-submit-letsencrypt');
  16487. const origBtnHtml = btn.innerHTML;
  16488. btn.disabled = true;
  16489. 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>`;
  16490. try {
  16491. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16492. method: 'POST',
  16493. headers: { 'Content-Type': 'application/json' },
  16494. body: JSON.stringify({
  16495. name: name,
  16496. domain: domain,
  16497. email: email,
  16498. staging: staging
  16499. })
  16500. });
  16501. if (!res.ok) {
  16502. const errData = await res.json();
  16503. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16504. }
  16505. closeLetsEncryptModal();
  16506. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16507. await loadCertificates();
  16508. } catch (err) {
  16509. showToast('Let\'s Encrypt Error', err.message, 'error');
  16510. } finally {
  16511. btn.disabled = false;
  16512. btn.innerHTML = origBtnHtml;
  16513. }
  16514. }
  16515. // Import Cert
  16516. function openImportCertModal() {
  16517. document.getElementById('form-import-cert').reset();
  16518. document.getElementById('modal-import-cert').classList.remove('hidden');
  16519. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16520. }
  16521. function closeImportCertModal() {
  16522. document.getElementById('modal-import-cert').classList.add('hidden');
  16523. }
  16524. async function submitImportCert(event) {
  16525. event.preventDefault();
  16526. const payload = {
  16527. name: document.getElementById('import-cert-name').value.trim(),
  16528. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16529. key_pem: document.getElementById('import-key-pem').value.trim()
  16530. };
  16531. try {
  16532. const res = await fetch(`${API_BASE}/certificates/import`, {
  16533. method: 'POST',
  16534. headers: { 'Content-Type': 'application/json' },
  16535. body: JSON.stringify(payload)
  16536. });
  16537. if (!res.ok) {
  16538. const errData = await res.json();
  16539. throw new Error(errData.message || 'Failed to import certificate');
  16540. }
  16541. closeImportCertModal();
  16542. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16543. await loadCertificates();
  16544. } catch (err) {
  16545. showToast('Error', err.message, 'error');
  16546. }
  16547. }
  16548. // View / Export Modal
  16549. async function openViewCertModal(name) {
  16550. const c = (state.certificates || []).find(x => x.name === name);
  16551. if (!c) return;
  16552. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16553. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16554. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16555. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16556. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16557. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16558. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16559. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16560. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16561. document.getElementById('modal-view-cert').classList.remove('hidden');
  16562. try {
  16563. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16564. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16565. const data = await res.json();
  16566. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16567. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16568. } catch (err) {
  16569. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16570. document.getElementById('view-key-pem-text').value = '';
  16571. }
  16572. }
  16573. function closeViewCertModal() {
  16574. document.getElementById('modal-view-cert').classList.add('hidden');
  16575. }
  16576. function copyCertPEM() {
  16577. const text = document.getElementById('view-cert-pem-text').value;
  16578. if (!text) return;
  16579. navigator.clipboard.writeText(text).then(() => {
  16580. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16581. }).catch(() => {
  16582. showToast('Error', 'Failed to copy to clipboard', 'error');
  16583. });
  16584. }
  16585. function copyKeyPEM() {
  16586. const text = document.getElementById('view-key-pem-text').value;
  16587. if (!text) return;
  16588. navigator.clipboard.writeText(text).then(() => {
  16589. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16590. }).catch(() => {
  16591. showToast('Error', 'Failed to copy to clipboard', 'error');
  16592. });
  16593. }
  16594. async function deleteCertificate(name) {
  16595. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16596. return;
  16597. }
  16598. try {
  16599. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16600. method: 'DELETE'
  16601. });
  16602. if (!res.ok) {
  16603. const errData = await res.json();
  16604. throw new Error(errData.message || 'Failed to delete certificate');
  16605. }
  16606. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16607. await loadCertificates();
  16608. } catch (err) {
  16609. showToast('Error', err.message, 'error');
  16610. }
  16611. }
  16612. // Refresh immediately when returning to a backgrounded controller tab.
  16613. document.addEventListener('visibilitychange', () => {
  16614. if (!state.currentUser) return;
  16615. if (document.hidden) {
  16616. if (trafficEventSource) trafficEventSource.close();
  16617. trafficEventSource = null;
  16618. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16619. trafficPollFallback = null;
  16620. } else {
  16621. fetchData(false);
  16622. initLiveTrafficStream();
  16623. if (state.activeTab === 'bwtest') loadBwTestView();
  16624. }
  16625. });
  16626. async function loadUpdateStatus(populate = true) {
  16627. try {
  16628. const res = await fetch(`${API_BASE}/update/status`);
  16629. if (!res.ok) throw new Error(await responseError(res));
  16630. const data = await res.json();
  16631. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16632. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16633. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16634. document.getElementById('update-state').textContent = data.state || 'idle';
  16635. document.getElementById('update-log').textContent = data.log || '';
  16636. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16637. }
  16638. async function saveUpdateConfig() {
  16639. try {
  16640. const repository = document.getElementById('update-repository').value.trim();
  16641. const branch = 'master';
  16642. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16643. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16644. if (!res.ok) throw new Error(await responseError(res));
  16645. document.getElementById('update-install-button').disabled = true;
  16646. document.getElementById('update-available').textContent = '—';
  16647. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16648. await loadUpdateStatus(false);
  16649. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16650. }
  16651. async function checkUpdate() {
  16652. try {
  16653. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16654. if (!res.ok) throw new Error(await responseError(res));
  16655. const data = await res.json();
  16656. document.getElementById('update-available').textContent = data.available_version;
  16657. document.getElementById('update-install-button').disabled = !data.update_available;
  16658. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16659. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16660. }
  16661. async function startUpdate(action) {
  16662. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16663. try {
  16664. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16665. if (!res.ok) throw new Error(await responseError(res));
  16666. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16667. await loadUpdateStatus(false);
  16668. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16669. }
  16670. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16671. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16672. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16673. function safeFirewallRow(row) {
  16674. const result = {...row};
  16675. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16676. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16677. return result;
  16678. }
  16679. function setFirewallDays(prefix, days) {
  16680. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16681. 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); }
  16682. }
  16683. function getFirewallDays(prefix) {
  16684. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16685. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16686. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16687. return selected.join(',');
  16688. }
  16689. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16690. const id = document.getElementById(kind+'-modal-id')?.value;
  16691. if (!id) { resetDisplay(); return; }
  16692. try {
  16693. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16694. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16695. resetDisplay(); await loadFirewall(false);
  16696. } catch(error) { showToast('Error', error.message, 'error'); }
  16697. }
  16698. function reviewLegacyFirewallSettings(kind, id) {
  16699. if (!id) return true;
  16700. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16701. const rule = (rows || []).find(r => r.id === id);
  16702. if (!rule) return true;
  16703. 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'];
  16704. const present = unsupported.filter(key => rule[key]);
  16705. if (!present.length) return true;
  16706. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16707. }
  16708. function refreshFirewallRejectTypes() {
  16709. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16710. const old=select.value;
  16711. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16712. 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'];
  16713. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16714. if(types.includes(old))select.value=old;
  16715. }
  16716. function setFirewallActionSelection(kind, value) {
  16717. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16718. if(!Array.from(select.options).some(option=>option.value===value)) {
  16719. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16720. }
  16721. select.value=value;
  16722. }
  16723. // ==========================================
  16724. // REVERSE PROXY & APPLICATION GATEWAY
  16725. // ==========================================
  16726. state.proxyRules = [];
  16727. state.proxyConfig = null;
  16728. async function loadReverseProxy(manual = false) {
  16729. try {
  16730. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16731. fetch(`${API_BASE}/proxy/config`),
  16732. fetch(`${API_BASE}/proxy/rules`),
  16733. fetch(`${API_BASE}/certificates`).catch(() => null)
  16734. ]);
  16735. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16736. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16737. state.proxyConfig = await cfgRes.json();
  16738. state.proxyRules = await rulesRes.json() || [];
  16739. if (certsRes && certsRes.ok) {
  16740. state.certificates = await certsRes.json() || [];
  16741. }
  16742. renderProxyRules(state.proxyRules);
  16743. updateProxyMetrics();
  16744. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16745. } catch (err) {
  16746. console.error('loadReverseProxy error:', err);
  16747. if (manual) showToast('Error', err.message, 'error');
  16748. }
  16749. }
  16750. function updateProxyMetrics() {
  16751. const badge = document.getElementById('badge-proxy-count');
  16752. if (badge) badge.textContent = (state.proxyRules || []).length;
  16753. const metricRules = document.getElementById('proxy-metric-rules');
  16754. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16755. const cfg = state.proxyConfig;
  16756. const statusEl = document.getElementById('proxy-metric-status');
  16757. const portsEl = document.getElementById('proxy-metric-ports');
  16758. if (cfg) {
  16759. if (statusEl) {
  16760. if (cfg.enabled) {
  16761. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16762. } else {
  16763. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16764. }
  16765. }
  16766. if (portsEl) {
  16767. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16768. }
  16769. }
  16770. let totalRequests = 0;
  16771. const certSet = new Set();
  16772. (state.proxyRules || []).forEach(r => {
  16773. totalRequests += (r.stats && r.stats.requests) || 0;
  16774. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16775. });
  16776. const metricRequests = document.getElementById('proxy-metric-requests');
  16777. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16778. const metricCerts = document.getElementById('proxy-metric-certs');
  16779. if (metricCerts) metricCerts.textContent = certSet.size;
  16780. }
  16781. function renderProxyRules(rules) {
  16782. const tbody = document.getElementById('proxy-rules-table-body');
  16783. if (!tbody) return;
  16784. if (!rules || rules.length === 0) {
  16785. 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>';
  16786. return;
  16787. }
  16788. tbody.innerHTML = rules.map(r => {
  16789. const isEnabled = r.enabled !== false;
  16790. 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>';
  16791. 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>`;
  16792. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16793. 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>';
  16794. 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>';
  16795. 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>` : '';
  16796. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16797. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16798. return `
  16799. <tr class="hover:bg-slate-800/40 transition">
  16800. <td class="py-3 px-4">
  16801. <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'}">
  16802. <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>
  16803. </button>
  16804. </td>
  16805. <td class="py-3 px-4">
  16806. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16807. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16808. </td>
  16809. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16810. ${domainsStr}
  16811. </td>
  16812. <td class="py-3 px-4">
  16813. ${pathBadge}
  16814. </td>
  16815. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16816. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16817. </td>
  16818. <td class="py-3 px-4 whitespace-nowrap">
  16819. ${protoBadge}${certBadge}
  16820. </td>
  16821. <td class="py-3 px-4 font-mono">
  16822. ${stripBadge}
  16823. </td>
  16824. <td class="py-3 px-4 font-mono text-slate-300">
  16825. ${requests}
  16826. </td>
  16827. <td class="py-3 px-4 text-right whitespace-nowrap">
  16828. <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>
  16829. <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>
  16830. </td>
  16831. </tr>
  16832. `;
  16833. }).join('');
  16834. }
  16835. function populateProxyCertDropdown(selectedVal = '') {
  16836. const select = document.getElementById('proxy-rule-cert');
  16837. if (!select) return;
  16838. const certs = state.certificates || [];
  16839. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16840. certs.filter(c => !c.is_ca).forEach(c => {
  16841. const opt = document.createElement('option');
  16842. opt.value = c.name;
  16843. const cn = c.common_name ? ` (${c.common_name})` : '';
  16844. opt.textContent = `${c.name}${cn}`;
  16845. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16846. opt.selected = true;
  16847. }
  16848. select.appendChild(opt);
  16849. });
  16850. }
  16851. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16852. const select = document.getElementById('proxy-cfg-default-cert');
  16853. if (!select) return;
  16854. const certs = state.certificates || [];
  16855. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16856. certs.filter(c => !c.is_ca).forEach(c => {
  16857. const opt = document.createElement('option');
  16858. opt.value = c.name;
  16859. const cn = c.common_name ? ` (${c.common_name})` : '';
  16860. opt.textContent = `${c.name}${cn}`;
  16861. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16862. opt.selected = true;
  16863. }
  16864. select.appendChild(opt);
  16865. });
  16866. }
  16867. function onProxyProtoChange() {
  16868. const proto = document.getElementById('proxy-rule-proto')?.value;
  16869. const certSelect = document.getElementById('proxy-rule-cert');
  16870. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16871. if (proto === 'http') {
  16872. if (certSelect) certSelect.disabled = true;
  16873. if (redirectCheck) redirectCheck.disabled = true;
  16874. } else {
  16875. if (certSelect) certSelect.disabled = false;
  16876. if (redirectCheck) redirectCheck.disabled = false;
  16877. }
  16878. }
  16879. function openAddProxyRuleModal() {
  16880. const modal = document.getElementById('modal-proxy-rule');
  16881. if (!modal) return;
  16882. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16883. <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>
  16884. <span>Add Reverse Proxy Rule</span>
  16885. `;
  16886. document.getElementById('proxy-rule-id').value = '';
  16887. document.getElementById('proxy-rule-name').value = '';
  16888. document.getElementById('proxy-rule-domains').value = '';
  16889. document.getElementById('proxy-rule-path').value = '/';
  16890. document.getElementById('proxy-rule-target').value = '';
  16891. document.getElementById('proxy-rule-proto').value = 'both';
  16892. document.getElementById('proxy-rule-strip-path').checked = false;
  16893. document.getElementById('proxy-rule-http-to-https').checked = false;
  16894. document.getElementById('proxy-rule-preserve-host').checked = false;
  16895. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16896. document.getElementById('proxy-rule-enabled').checked = true;
  16897. document.getElementById('proxy-rule-comment').value = '';
  16898. populateProxyCertDropdown('');
  16899. onProxyProtoChange();
  16900. modal.classList.remove('hidden');
  16901. }
  16902. function openEditProxyRuleModal(id) {
  16903. const modal = document.getElementById('modal-proxy-rule');
  16904. if (!modal) return;
  16905. const rule = (state.proxyRules || []).find(r => r.id === id);
  16906. if (!rule) {
  16907. showToast('Error', 'Rule not found', 'error');
  16908. return;
  16909. }
  16910. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16911. <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>
  16912. <span>Edit Reverse Proxy Rule</span>
  16913. `;
  16914. document.getElementById('proxy-rule-id').value = rule.id || '';
  16915. document.getElementById('proxy-rule-name').value = rule.name || '';
  16916. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16917. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16918. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16919. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16920. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16921. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16922. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16923. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16924. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16925. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16926. populateProxyCertDropdown(rule.certificate || '');
  16927. onProxyProtoChange();
  16928. modal.classList.remove('hidden');
  16929. }
  16930. function closeProxyRuleModal() {
  16931. const modal = document.getElementById('modal-proxy-rule');
  16932. if (modal) modal.classList.add('hidden');
  16933. }
  16934. async function saveProxyRule(event) {
  16935. event.preventDefault();
  16936. const id = document.getElementById('proxy-rule-id').value;
  16937. const name = document.getElementById('proxy-rule-name').value.trim();
  16938. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16939. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16940. const target = document.getElementById('proxy-rule-target').value.trim();
  16941. const proto = document.getElementById('proxy-rule-proto').value;
  16942. const cert = document.getElementById('proxy-rule-cert').value;
  16943. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16944. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16945. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16946. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16947. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16948. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16949. let domains = [];
  16950. if (rawDomains && rawDomains !== '*') {
  16951. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16952. }
  16953. const payload = {
  16954. id: id || undefined,
  16955. name,
  16956. domains,
  16957. path: pathVal,
  16958. target_url: target,
  16959. protocol: proto,
  16960. certificate: cert,
  16961. strip_path: stripPath,
  16962. http_to_https: httpToHttps,
  16963. preserve_host: preserveHost,
  16964. insecure_tls: insecureTLS,
  16965. enabled,
  16966. comment
  16967. };
  16968. try {
  16969. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16970. const method = id ? 'PUT' : 'POST';
  16971. const res = await fetch(url, {
  16972. method,
  16973. headers: { 'Content-Type': 'application/json' },
  16974. body: JSON.stringify(payload)
  16975. });
  16976. if (!res.ok) {
  16977. const errData = await res.json().catch(() => ({}));
  16978. throw new Error(errData.message || 'Failed to save proxy rule');
  16979. }
  16980. closeProxyRuleModal();
  16981. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  16982. await loadReverseProxy(false);
  16983. } catch (err) {
  16984. showToast('Error', err.message, 'error');
  16985. }
  16986. }
  16987. async function deleteProxyRule(id) {
  16988. const rule = (state.proxyRules || []).find(r => r.id === id);
  16989. const name = rule ? rule.name : id;
  16990. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  16991. return;
  16992. }
  16993. try {
  16994. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  16995. method: 'DELETE'
  16996. });
  16997. if (!res.ok) {
  16998. const errData = await res.json().catch(() => ({}));
  16999. throw new Error(errData.message || 'Failed to delete rule');
  17000. }
  17001. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17002. await loadReverseProxy(false);
  17003. } catch (err) {
  17004. showToast('Error', err.message, 'error');
  17005. }
  17006. }
  17007. async function toggleProxyRuleState(id, currentState) {
  17008. try {
  17009. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17010. method: 'POST',
  17011. headers: { 'Content-Type': 'application/json' },
  17012. body: JSON.stringify({ enabled: !currentState })
  17013. });
  17014. if (!res.ok) {
  17015. const errData = await res.json().catch(() => ({}));
  17016. throw new Error(errData.message || 'Failed to toggle rule state');
  17017. }
  17018. await loadReverseProxy(false);
  17019. } catch (err) {
  17020. showToast('Error', err.message, 'error');
  17021. }
  17022. }
  17023. function openProxyConfigModal() {
  17024. const modal = document.getElementById('modal-proxy-config');
  17025. if (!modal) return;
  17026. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17027. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17028. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17029. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17030. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17031. modal.classList.remove('hidden');
  17032. }
  17033. function closeProxyConfigModal() {
  17034. const modal = document.getElementById('modal-proxy-config');
  17035. if (modal) modal.classList.add('hidden');
  17036. }
  17037. async function saveProxyConfig(event) {
  17038. event.preventDefault();
  17039. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17040. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17041. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17042. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17043. const payload = {
  17044. enabled,
  17045. http_port: httpPort,
  17046. https_port: httpsPort,
  17047. default_cert: defaultCert
  17048. };
  17049. try {
  17050. const res = await fetch(`${API_BASE}/proxy/config`, {
  17051. method: 'POST',
  17052. headers: { 'Content-Type': 'application/json' },
  17053. body: JSON.stringify(payload)
  17054. });
  17055. if (!res.ok) {
  17056. const errData = await res.json().catch(() => ({}));
  17057. throw new Error(errData.message || 'Failed to update proxy settings');
  17058. }
  17059. closeProxyConfigModal();
  17060. showToast('Success', 'Reverse proxy settings updated', 'success');
  17061. await loadReverseProxy(false);
  17062. } catch (err) {
  17063. showToast('Error', err.message, 'error');
  17064. }
  17065. }
  17066. // ==================== SD-WAN Controller ====================
  17067. async function loadSDWAN(manual = false) {
  17068. try {
  17069. const [groupsRes, telemetryRes] = await Promise.all([
  17070. fetch(`${API_BASE}/sdwan/groups`),
  17071. fetch(`${API_BASE}/sdwan/telemetry`)
  17072. ]);
  17073. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17074. state.sdwanGroups = await groupsRes.json() || [];
  17075. if (telemetryRes.ok) {
  17076. state.sdwanTelemetry = await telemetryRes.json() || {};
  17077. }
  17078. renderSDWANGroups(state.sdwanGroups);
  17079. renderSDWANMembers(state.sdwanGroups);
  17080. updateSDWANMetrics(state.sdwanTelemetry);
  17081. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17082. } catch (err) {
  17083. console.error('loadSDWAN error:', err);
  17084. if (manual) showToast('Error', err.message, 'error');
  17085. }
  17086. }
  17087. function updateSDWANMetrics(telemetry) {
  17088. const groups = state.sdwanGroups || [];
  17089. const t = telemetry || {};
  17090. const badge = document.getElementById('badge-sdwan-count');
  17091. if (badge) badge.textContent = groups.length;
  17092. const metricGroups = document.getElementById('sdwan-metric-groups');
  17093. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17094. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17095. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17096. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17097. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17098. const metricDown = document.getElementById('sdwan-metric-down');
  17099. if (metricDown) metricDown.textContent = t.down_members || 0;
  17100. }
  17101. function renderSDWANGroups(groups) {
  17102. const tbody = document.getElementById('sdwan-groups-table-body');
  17103. if (!tbody) return;
  17104. if (!groups || groups.length === 0) {
  17105. 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>';
  17106. return;
  17107. }
  17108. tbody.innerHTML = groups.map(g => {
  17109. const isEnabled = g.disabled !== true;
  17110. const members = g.members || [];
  17111. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17112. // Build distribution progress bar
  17113. let distHtml = '';
  17114. if (members.length === 0) {
  17115. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17116. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17117. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17118. const segments = members.map((m, idx) => {
  17119. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17120. const col = colors[idx % colors.length];
  17121. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17122. }).join('');
  17123. const labels = members.map((m, idx) => {
  17124. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17125. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17126. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17127. }).join('');
  17128. distHtml = `
  17129. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17130. <div class="flex flex-wrap">${labels}</div>
  17131. `;
  17132. } else if (g.mode === 'lowest-latency') {
  17133. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17134. } else if (g.mode === 'lowest-loss') {
  17135. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17136. } else if (g.mode === 'failover') {
  17137. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17138. }
  17139. let modeBadge = '';
  17140. switch (g.mode) {
  17141. case 'weighted':
  17142. 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>';
  17143. break;
  17144. case 'pcc':
  17145. 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>';
  17146. break;
  17147. case 'lowest-latency':
  17148. 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>';
  17149. break;
  17150. case 'lowest-loss':
  17151. 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>';
  17152. break;
  17153. case 'failover':
  17154. 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>';
  17155. break;
  17156. default:
  17157. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17158. }
  17159. const autoNatBadge = g.auto_nat
  17160. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17161. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17162. return `
  17163. <tr class="hover:bg-slate-800/40 transition">
  17164. <td class="py-3 px-4">
  17165. <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'}">
  17166. <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>
  17167. </button>
  17168. </td>
  17169. <td class="py-3 px-4">
  17170. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17171. <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>
  17172. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17173. </div>
  17174. </td>
  17175. <td class="py-3 px-4">${modeBadge}</td>
  17176. <td class="py-3 px-4">${distHtml}</td>
  17177. <td class="py-3 px-4">
  17178. <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>
  17179. </td>
  17180. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17181. <td class="py-3 px-4">${autoNatBadge}</td>
  17182. <td class="py-3 px-4 text-right">
  17183. <div class="flex items-center justify-end gap-1.5">
  17184. <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">
  17185. <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>
  17186. </button>
  17187. <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">
  17188. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
  17189. </button>
  17190. <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">
  17191. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
  17192. </button>
  17193. </div>
  17194. </td>
  17195. </tr>
  17196. `;
  17197. }).join('');
  17198. }
  17199. function renderSDWANMembers(groups) {
  17200. const tbody = document.getElementById('sdwan-members-table-body');
  17201. if (!tbody) return;
  17202. const allMembers = [];
  17203. (groups || []).forEach(g => {
  17204. (g.members || []).forEach(m => {
  17205. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17206. });
  17207. });
  17208. if (allMembers.length === 0) {
  17209. 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>';
  17210. return;
  17211. }
  17212. tbody.innerHTML = allMembers.map(m => {
  17213. const isEnabled = m.disabled !== true;
  17214. 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>';
  17215. if (!isEnabled) {
  17216. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17217. } else if (m.status === 'DEGRADED') {
  17218. 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>';
  17219. } else if (m.status === 'DOWN') {
  17220. 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>';
  17221. }
  17222. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17223. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17224. return `
  17225. <tr class="hover:bg-slate-800/40 transition">
  17226. <td class="py-3 px-4">
  17227. <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'}">
  17228. <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>
  17229. </button>
  17230. </td>
  17231. <td class="py-3 px-4">
  17232. <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>
  17233. </td>
  17234. <td class="py-3 px-4">
  17235. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17236. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17237. </td>
  17238. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17239. <td class="py-3 px-4">
  17240. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17241. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17242. </td>
  17243. <td class="py-3 px-4">${statusBadge}</td>
  17244. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17245. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17246. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17247. </td>
  17248. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17249. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17250. </td>
  17251. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17252. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17253. </td>
  17254. <td class="py-3 px-4 text-right">
  17255. <div class="flex items-center justify-end gap-1.5">
  17256. <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">
  17257. <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>
  17258. </button>
  17259. <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">
  17260. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
  17261. </button>
  17262. </div>
  17263. </td>
  17264. </tr>
  17265. `;
  17266. }).join('');
  17267. }
  17268. // Modal handling for SD-WAN Groups
  17269. function openAddSDWANGroupModal() {
  17270. const modal = document.getElementById('modal-sdwan-group');
  17271. if (!modal) return;
  17272. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17273. document.getElementById('sdwan-group-id').value = '';
  17274. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17275. document.getElementById('sdwan-group-name').disabled = false;
  17276. document.getElementById('sdwan-group-mode').value = 'weighted';
  17277. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17278. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17279. document.getElementById('sdwan-group-probe-interval').value = 3;
  17280. document.getElementById('sdwan-group-auto-nat').checked = true;
  17281. document.getElementById('sdwan-group-comment').value = '';
  17282. modal.classList.remove('hidden');
  17283. }
  17284. function openEditSDWANGroupModal(id) {
  17285. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17286. if (!group) return;
  17287. const modal = document.getElementById('modal-sdwan-group');
  17288. if (!modal) return;
  17289. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17290. document.getElementById('sdwan-group-id').value = group.id;
  17291. document.getElementById('sdwan-group-name').value = group.name;
  17292. document.getElementById('sdwan-group-name').disabled = true;
  17293. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17294. if (group.mode === 'pcc') {
  17295. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17296. } else {
  17297. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17298. }
  17299. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17300. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17301. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17302. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17303. modal.classList.remove('hidden');
  17304. }
  17305. function closeSDWANGroupModal() {
  17306. const modal = document.getElementById('modal-sdwan-group');
  17307. if (modal) modal.classList.add('hidden');
  17308. }
  17309. function onSDWANModeChange() {
  17310. const mode = document.getElementById('sdwan-group-mode').value;
  17311. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17312. if (pccContainer) {
  17313. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17314. else pccContainer.classList.add('hidden');
  17315. }
  17316. }
  17317. async function saveSDWANGroup(event) {
  17318. event.preventDefault();
  17319. const id = document.getElementById('sdwan-group-id').value;
  17320. const name = document.getElementById('sdwan-group-name').value.trim();
  17321. const mode = document.getElementById('sdwan-group-mode').value;
  17322. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17323. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17324. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17325. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17326. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17327. const payload = {
  17328. id: id || undefined,
  17329. name,
  17330. mode,
  17331. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17332. probe_interval: probeInterval,
  17333. auto_nat: autoNAT,
  17334. comment,
  17335. members: existing ? existing.members : undefined
  17336. };
  17337. try {
  17338. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17339. method: 'POST',
  17340. headers: { 'Content-Type': 'application/json' },
  17341. body: JSON.stringify(payload)
  17342. });
  17343. if (!res.ok) {
  17344. const err = await res.json().catch(() => ({}));
  17345. throw new Error(err.message || 'Failed to save SD-WAN group');
  17346. }
  17347. closeSDWANGroupModal();
  17348. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17349. await loadSDWAN(false);
  17350. } catch (err) {
  17351. showToast('Error', err.message, 'error');
  17352. }
  17353. }
  17354. async function toggleSDWANGroupState(id, currentState) {
  17355. try {
  17356. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17357. method: 'POST',
  17358. headers: { 'Content-Type': 'application/json' },
  17359. body: JSON.stringify({ disabled: currentState })
  17360. });
  17361. if (!res.ok) throw new Error('Failed to update group state');
  17362. await loadSDWAN(false);
  17363. } catch (err) {
  17364. showToast('Error', err.message, 'error');
  17365. }
  17366. }
  17367. async function deleteSDWANGroup(id) {
  17368. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17369. const name = group ? group.name : id;
  17370. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17371. try {
  17372. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17373. method: 'DELETE'
  17374. });
  17375. if (!res.ok) {
  17376. const err = await res.json().catch(() => ({}));
  17377. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17378. }
  17379. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17380. await loadSDWAN(false);
  17381. } catch (err) {
  17382. showToast('Error', err.message, 'error');
  17383. }
  17384. }
  17385. // Modal handling for SD-WAN Members
  17386. function populateSDWANGroupsSelect(selectedId = '') {
  17387. const sel = document.getElementById('sdwan-member-group-id');
  17388. if (!sel) return;
  17389. sel.innerHTML = '';
  17390. (state.sdwanGroups || []).forEach(g => {
  17391. const opt = document.createElement('option');
  17392. opt.value = g.id;
  17393. opt.textContent = `${g.name} (${g.mode})`;
  17394. if (g.id === selectedId) opt.selected = true;
  17395. sel.appendChild(opt);
  17396. });
  17397. }
  17398. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17399. const sel = document.getElementById('sdwan-member-interface');
  17400. if (!sel) return;
  17401. sel.innerHTML = '';
  17402. (state.interfaces || []).forEach(i => {
  17403. const opt = document.createElement('option');
  17404. opt.value = i.name;
  17405. opt.textContent = `${i.name} (${i.role || i.type})`;
  17406. if (i.name === selectedVal) opt.selected = true;
  17407. sel.appendChild(opt);
  17408. });
  17409. }
  17410. function openAddSDWANMemberModal(defaultGroupId = null) {
  17411. const modal = document.getElementById('modal-sdwan-member');
  17412. if (!modal) return;
  17413. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17414. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17415. return;
  17416. }
  17417. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17418. document.getElementById('sdwan-member-id').value = '';
  17419. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17420. populateSDWANMemberInterfaceSelect();
  17421. document.getElementById('sdwan-member-gateway').value = '';
  17422. document.getElementById('sdwan-member-weight').value = 50;
  17423. document.getElementById('sdwan-member-priority').value = 1;
  17424. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17425. document.getElementById('sdwan-member-max-lat').value = 250;
  17426. document.getElementById('sdwan-member-max-loss').value = 20;
  17427. document.getElementById('sdwan-member-comment').value = '';
  17428. modal.classList.remove('hidden');
  17429. }
  17430. function openEditSDWANMemberModal(groupId, memberId) {
  17431. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17432. if (!group) return;
  17433. const member = (group.members || []).find(m => m.id === memberId);
  17434. if (!member) return;
  17435. const modal = document.getElementById('modal-sdwan-member');
  17436. if (!modal) return;
  17437. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17438. document.getElementById('sdwan-member-id').value = member.id;
  17439. populateSDWANGroupsSelect(group.id);
  17440. document.getElementById('sdwan-member-group-id').disabled = true;
  17441. populateSDWANMemberInterfaceSelect(member.interface);
  17442. document.getElementById('sdwan-member-interface').disabled = true;
  17443. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17444. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17445. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17446. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17447. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17448. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17449. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17450. modal.classList.remove('hidden');
  17451. }
  17452. function closeSDWANMemberModal() {
  17453. const modal = document.getElementById('modal-sdwan-member');
  17454. if (modal) {
  17455. document.getElementById('sdwan-member-group-id').disabled = false;
  17456. document.getElementById('sdwan-member-interface').disabled = false;
  17457. modal.classList.add('hidden');
  17458. }
  17459. }
  17460. async function saveSDWANMember(event) {
  17461. event.preventDefault();
  17462. const id = document.getElementById('sdwan-member-id').value;
  17463. let groupId = document.getElementById('sdwan-member-group-id').value;
  17464. let iface = document.getElementById('sdwan-member-interface').value;
  17465. // In edit mode with disabled selects, fallback to existing member data if needed
  17466. if (id) {
  17467. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17468. if (existingGroup) {
  17469. if (!groupId) groupId = existingGroup.id;
  17470. const mem = (existingGroup.members || []).find(m => m.id === id);
  17471. if (mem && !iface) iface = mem.interface;
  17472. }
  17473. }
  17474. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17475. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17476. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17477. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17478. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17479. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17480. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17481. const payload = {
  17482. id: id || undefined,
  17483. interface: iface,
  17484. gateway,
  17485. weight,
  17486. priority,
  17487. target_probe: targetProbe,
  17488. max_latency: maxLatency,
  17489. max_loss: maxLoss,
  17490. comment
  17491. };
  17492. try {
  17493. const method = id ? 'PUT' : 'POST';
  17494. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17495. method,
  17496. headers: { 'Content-Type': 'application/json' },
  17497. body: JSON.stringify(payload)
  17498. });
  17499. if (!res.ok) {
  17500. const err = await res.json().catch(() => ({}));
  17501. throw new Error(err.message || 'Failed to save member link');
  17502. }
  17503. closeSDWANMemberModal();
  17504. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17505. await loadSDWAN(false);
  17506. } catch (err) {
  17507. showToast('Error', err.message, 'error');
  17508. }
  17509. }
  17510. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17511. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17512. if (!group) return;
  17513. const member = (group.members || []).find(m => m.id === memberId);
  17514. if (!member) return;
  17515. const payload = {
  17516. ...member,
  17517. disabled: currentState
  17518. };
  17519. try {
  17520. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17521. method: 'PUT',
  17522. headers: { 'Content-Type': 'application/json' },
  17523. body: JSON.stringify(payload)
  17524. });
  17525. if (!res.ok) throw new Error('Failed to update member state');
  17526. await loadSDWAN(false);
  17527. } catch (err) {
  17528. showToast('Error', err.message, 'error');
  17529. }
  17530. }
  17531. async function deleteSDWANMember(groupId, iface) {
  17532. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17533. try {
  17534. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17535. method: 'DELETE'
  17536. });
  17537. if (!res.ok) {
  17538. const err = await res.json().catch(() => ({}));
  17539. throw new Error(err.message || 'Failed to remove member link');
  17540. }
  17541. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17542. await loadSDWAN(false);
  17543. } catch (err) {
  17544. showToast('Error', err.message, 'error');
  17545. }
  17546. }
  17547. // ==============================================================================
  17548. // DYNAMIC ROUTING: RIP MODULE
  17549. // ==============================================================================
  17550. state.ripInstances = [];
  17551. state.ripInterfaces = [];
  17552. state.ripNeighborsLive = [];
  17553. state.ripRoutes = [];
  17554. state.selectedRipRow = {};
  17555. state.activeRipTab = 'instances';
  17556. function switchRipTab(tab) {
  17557. state.activeRipTab = tab;
  17558. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17559. const pane = document.getElementById(`rip-pane-${t}`);
  17560. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17561. if (pane) {
  17562. if (t === tab) pane.classList.remove('hidden');
  17563. else pane.classList.add('hidden');
  17564. }
  17565. if (btn) {
  17566. if (t === tab) {
  17567. 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';
  17568. } else {
  17569. 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';
  17570. }
  17571. }
  17572. });
  17573. }
  17574. function selectRipRow(tab, id) {
  17575. if (!state.selectedRipRow) state.selectedRipRow = {};
  17576. state.selectedRipRow[tab] = id;
  17577. if (tab === 'instances') {
  17578. renderRipInstances();
  17579. const btnEn = document.getElementById('btn-rip-inst-enable');
  17580. const btnDis = document.getElementById('btn-rip-inst-disable');
  17581. const btnRem = document.getElementById('btn-rip-inst-remove');
  17582. if (btnEn) btnEn.disabled = false;
  17583. if (btnDis) btnDis.disabled = false;
  17584. if (btnRem) btnRem.disabled = false;
  17585. } else if (tab === 'interfaces') {
  17586. renderRipInterfaces();
  17587. const btnEn = document.getElementById('btn-rip-iface-enable');
  17588. const btnDis = document.getElementById('btn-rip-iface-disable');
  17589. const btnRem = document.getElementById('btn-rip-iface-remove');
  17590. if (btnEn) btnEn.disabled = false;
  17591. if (btnDis) btnDis.disabled = false;
  17592. if (btnRem) btnRem.disabled = false;
  17593. }
  17594. }
  17595. function renderRipInstances() {
  17596. const tbody = document.getElementById('rip-instances-table-body');
  17597. if (!tbody) return;
  17598. const countEl = document.getElementById('rip-instances-footer-count');
  17599. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17600. let list = state.ripInstances || [];
  17601. if (filter) {
  17602. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17603. }
  17604. if (countEl) countEl.innerText = list.length;
  17605. const selId = state.selectedRipRow?.instances;
  17606. tbody.innerHTML = list.map((inst, idx) => {
  17607. const isSel = inst.id === selId;
  17608. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17609. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400">R</span>';
  17610. const redist = [];
  17611. if (inst.redistribute_connected) redist.push('conn');
  17612. if (inst.redistribute_static) redist.push('static');
  17613. if (inst.redistribute_bgp) redist.push('bgp');
  17614. if (inst.redistribute_ospf) redist.push('ospf');
  17615. if (inst.redistribute_default) redist.push('default');
  17616. return `
  17617. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17618. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17619. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17620. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17621. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17622. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17623. </td>
  17624. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${escapeHtml(inst.version || 'rip2')}</td>
  17625. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17626. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17627. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17628. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17629. </tr>
  17630. `;
  17631. }).join('');
  17632. }
  17633. function renderRipInterfaces() {
  17634. const tbody = document.getElementById('rip-interfaces-table-body');
  17635. if (!tbody) return;
  17636. const countEl = document.getElementById('rip-interfaces-footer-count');
  17637. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17638. let list = state.ripInterfaces || [];
  17639. if (filter) {
  17640. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17641. }
  17642. if (countEl) countEl.innerText = list.length;
  17643. const selId = state.selectedRipRow?.interfaces;
  17644. tbody.innerHTML = list.map((iface, idx) => {
  17645. const isSel = iface.id === selId;
  17646. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17647. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17648. return `
  17649. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17650. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17651. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17652. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17653. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17654. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17655. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17656. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17657. <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>
  17658. </tr>
  17659. `;
  17660. }).join('');
  17661. }
  17662. function renderRipNeighbors() {
  17663. const tbody = document.getElementById('rip-neighbors-table-body');
  17664. if (!tbody) return;
  17665. const countEl = document.getElementById('rip-neighbors-footer-count');
  17666. const list = state.ripNeighborsLive || [];
  17667. if (countEl) countEl.innerText = list.length;
  17668. tbody.innerHTML = list.map((nbr, idx) => `
  17669. <tr class="hover:bg-[#1a2636] text-slate-300">
  17670. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17671. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17672. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17673. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17674. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17675. </tr>
  17676. `).join('');
  17677. }
  17678. function renderRipRoutes() {
  17679. const tbody = document.getElementById('rip-routes-table-body');
  17680. if (!tbody) return;
  17681. const countEl = document.getElementById('rip-routes-footer-count');
  17682. const list = state.ripRoutes || [];
  17683. if (countEl) countEl.innerText = list.length;
  17684. tbody.innerHTML = list.map((r, idx) => `
  17685. <tr class="hover:bg-[#1a2636] text-slate-300">
  17686. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17687. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17688. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17689. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17690. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17691. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17692. </tr>
  17693. `).join('');
  17694. }
  17695. function openRipInstanceModal() {
  17696. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17697. document.getElementById('modal-rip-instance-id').value = '';
  17698. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17699. document.getElementById('modal-rip-instance-version').value = 'rip2';
  17700. document.getElementById('modal-rip-instance-update').value = '30';
  17701. document.getElementById('modal-rip-instance-timeout').value = '180';
  17702. document.getElementById('modal-rip-instance-garbage').value = '120';
  17703. document.getElementById('modal-rip-instance-metric').value = '1';
  17704. document.getElementById('modal-rip-instance-comment').value = '';
  17705. document.getElementById('modal-rip-instance-enabled').checked = true;
  17706. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17707. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17708. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17709. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17710. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17711. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17712. }
  17713. function openEditRipInstanceModal(id) {
  17714. const inst = (state.ripInstances || []).find(i => i.id === id);
  17715. if (!inst) return;
  17716. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17717. document.getElementById('modal-rip-instance-id').value = inst.id;
  17718. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17719. document.getElementById('modal-rip-instance-version').value = inst.version || 'rip2';
  17720. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17721. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17722. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17723. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17724. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17725. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17726. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17727. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17728. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17729. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17730. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17731. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17732. }
  17733. function closeRipInstanceModal() {
  17734. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17735. }
  17736. async function submitRipInstance(e) {
  17737. e.preventDefault();
  17738. const id = document.getElementById('modal-rip-instance-id').value;
  17739. const payload = {
  17740. id: id || undefined,
  17741. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17742. version: document.getElementById('modal-rip-instance-version').value,
  17743. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17744. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17745. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17746. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17747. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17748. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17749. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17750. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17751. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17752. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17753. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17754. };
  17755. try {
  17756. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17757. method: 'POST',
  17758. headers: { 'Content-Type': 'application/json' },
  17759. body: JSON.stringify(payload)
  17760. });
  17761. if (!res.ok) throw new Error(await res.text());
  17762. closeRipInstanceModal();
  17763. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17764. await loadDynamicRouting(false);
  17765. } catch (err) {
  17766. showToast('Error', err.message, 'error');
  17767. }
  17768. }
  17769. async function enableSelectedRipInstance() {
  17770. const id = state.selectedRipRow?.instances;
  17771. if (!id) return;
  17772. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17773. await loadDynamicRouting(false);
  17774. }
  17775. async function disableSelectedRipInstance() {
  17776. const id = state.selectedRipRow?.instances;
  17777. if (!id) return;
  17778. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17779. await loadDynamicRouting(false);
  17780. }
  17781. async function removeSelectedRipInstance() {
  17782. const id = state.selectedRipRow?.instances;
  17783. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17784. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17785. state.selectedRipRow.instances = null;
  17786. await loadDynamicRouting(false);
  17787. }
  17788. function openRipInterfaceModal() {
  17789. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17790. document.getElementById('modal-rip-iface-id').value = '';
  17791. document.getElementById('modal-rip-iface-pattern').value = '';
  17792. document.getElementById('modal-rip-iface-instance').value = 'rip1';
  17793. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17794. document.getElementById('modal-rip-iface-metric').value = '1';
  17795. document.getElementById('modal-rip-iface-comment').value = '';
  17796. document.getElementById('modal-rip-iface-enabled').checked = true;
  17797. document.getElementById('modal-rip-iface-passive').checked = false;
  17798. document.getElementById('modal-rip-iface-bfd').checked = false;
  17799. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17800. }
  17801. function openEditRipInterfaceModal(id) {
  17802. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17803. if (!iface) return;
  17804. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17805. document.getElementById('modal-rip-iface-id').value = iface.id;
  17806. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '';
  17807. document.getElementById('modal-rip-iface-instance').value = iface.instance || '';
  17808. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17809. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17810. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17811. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17812. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17813. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17814. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17815. }
  17816. function closeRipInterfaceModal() {
  17817. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17818. }
  17819. async function submitRipInterface(e) {
  17820. e.preventDefault();
  17821. const id = document.getElementById('modal-rip-iface-id').value;
  17822. const payload = {
  17823. id: id || undefined,
  17824. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17825. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17826. mode: document.getElementById('modal-rip-iface-mode').value,
  17827. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17828. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17829. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17830. passive: document.getElementById('modal-rip-iface-passive').checked,
  17831. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17832. };
  17833. try {
  17834. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17835. method: 'POST',
  17836. headers: { 'Content-Type': 'application/json' },
  17837. body: JSON.stringify(payload)
  17838. });
  17839. if (!res.ok) throw new Error(await res.text());
  17840. closeRipInterfaceModal();
  17841. showToast('Saved', `RIP interface template saved`, 'success');
  17842. await loadDynamicRouting(false);
  17843. } catch (err) {
  17844. showToast('Error', err.message, 'error');
  17845. }
  17846. }
  17847. async function enableSelectedRipInterface() {
  17848. const id = state.selectedRipRow?.interfaces;
  17849. if (!id) return;
  17850. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17851. await loadDynamicRouting(false);
  17852. }
  17853. async function disableSelectedRipInterface() {
  17854. const id = state.selectedRipRow?.interfaces;
  17855. if (!id) return;
  17856. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17857. await loadDynamicRouting(false);
  17858. }
  17859. async function removeSelectedRipInterface() {
  17860. const id = state.selectedRipRow?.interfaces;
  17861. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17862. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17863. state.selectedRipRow.interfaces = null;
  17864. await loadDynamicRouting(false);
  17865. }
  17866. // ==============================================================================
  17867. // DYNAMIC ROUTING: BFD MODULE
  17868. // ==============================================================================
  17869. state.bfdInstance = null;
  17870. state.bfdInterfaces = [];
  17871. state.bfdNeighbors = [];
  17872. state.bfdSessions = [];
  17873. state.selectedBfdRow = {};
  17874. state.activeBfdTab = 'config';
  17875. function switchBfdTab(tab) {
  17876. state.activeBfdTab = tab;
  17877. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  17878. const pane = document.getElementById(`bfd-pane-${t}`);
  17879. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  17880. if (pane) {
  17881. if (t === tab) pane.classList.remove('hidden');
  17882. else pane.classList.add('hidden');
  17883. }
  17884. if (btn) {
  17885. if (t === tab) {
  17886. 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';
  17887. } else {
  17888. 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';
  17889. }
  17890. }
  17891. });
  17892. }
  17893. function selectBfdRow(tab, id) {
  17894. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  17895. state.selectedBfdRow[tab] = id;
  17896. if (tab === 'interfaces') {
  17897. renderBfdInterfaces();
  17898. const btnEn = document.getElementById('btn-bfd-iface-enable');
  17899. const btnDis = document.getElementById('btn-bfd-iface-disable');
  17900. const btnRem = document.getElementById('btn-bfd-iface-remove');
  17901. if (btnEn) btnEn.disabled = false;
  17902. if (btnDis) btnDis.disabled = false;
  17903. if (btnRem) btnRem.disabled = false;
  17904. } else if (tab === 'peers') {
  17905. renderBfdPeers();
  17906. const btnEn = document.getElementById('btn-bfd-peer-enable');
  17907. const btnDis = document.getElementById('btn-bfd-peer-disable');
  17908. const btnRem = document.getElementById('btn-bfd-peer-remove');
  17909. if (btnEn) btnEn.disabled = false;
  17910. if (btnDis) btnDis.disabled = false;
  17911. if (btnRem) btnRem.disabled = false;
  17912. }
  17913. }
  17914. function renderBfdConfig() {
  17915. const inst = state.bfdInstance;
  17916. const pill = document.getElementById('bfd-live-status-pill');
  17917. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  17918. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  17919. const peerStat = document.getElementById('bfd-stat-peers');
  17920. const sessStat = document.getElementById('bfd-stat-sessions');
  17921. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  17922. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  17923. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  17924. if (!inst || inst.disabled) {
  17925. if (pill) {
  17926. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  17927. pill.innerText = 'DISABLED';
  17928. }
  17929. if (toggleBtn) {
  17930. toggleBtn.innerText = 'Enable BFD';
  17931. 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';
  17932. }
  17933. } else {
  17934. if (pill) {
  17935. 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';
  17936. pill.innerText = inst.running ? 'RUNNING (ACTIVE)' : 'CONFIGURED';
  17937. }
  17938. if (toggleBtn) {
  17939. toggleBtn.innerText = 'Disable BFD';
  17940. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  17941. }
  17942. }
  17943. }
  17944. async function toggleBfdGlobalState() {
  17945. const current = state.bfdInstance;
  17946. const newDisabled = current ? !current.disabled : false;
  17947. try {
  17948. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  17949. method: 'POST',
  17950. headers: { 'Content-Type': 'application/json' },
  17951. body: JSON.stringify({ enabled: !newDisabled, disabled: newDisabled })
  17952. });
  17953. if (!res.ok) throw new Error(await res.text());
  17954. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  17955. await loadDynamicRouting(false);
  17956. } catch (err) {
  17957. showToast('Error', err.message, 'error');
  17958. }
  17959. }
  17960. function renderBfdInterfaces() {
  17961. const tbody = document.getElementById('bfd-interfaces-table-body');
  17962. if (!tbody) return;
  17963. const countEl = document.getElementById('bfd-interfaces-footer-count');
  17964. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  17965. let list = state.bfdInterfaces || [];
  17966. if (filter) {
  17967. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17968. }
  17969. if (countEl) countEl.innerText = list.length;
  17970. const selId = state.selectedBfdRow?.interfaces;
  17971. tbody.innerHTML = list.map((iface, idx) => {
  17972. const isSel = iface.id === selId;
  17973. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  17974. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  17975. return `
  17976. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  17977. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17978. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17979. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17980. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17981. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  17982. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  17983. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  17984. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  17985. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17986. </tr>
  17987. `;
  17988. }).join('');
  17989. }
  17990. function renderBfdPeers() {
  17991. const tbody = document.getElementById('bfd-peers-table-body');
  17992. if (!tbody) return;
  17993. const countEl = document.getElementById('bfd-peers-footer-count');
  17994. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  17995. let list = state.bfdNeighbors || [];
  17996. if (filter) {
  17997. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  17998. }
  17999. if (countEl) countEl.innerText = list.length;
  18000. const selId = state.selectedBfdRow?.peers;
  18001. tbody.innerHTML = list.map((p, idx) => {
  18002. const isSel = p.id === selId;
  18003. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18004. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18005. return `
  18006. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18007. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18008. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18009. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18010. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18011. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18012. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18013. </tr>
  18014. `;
  18015. }).join('');
  18016. }
  18017. function renderBfdSessions() {
  18018. const tbody = document.getElementById('bfd-sessions-table-body');
  18019. if (!tbody) return;
  18020. const countEl = document.getElementById('bfd-sessions-footer-count');
  18021. const list = state.bfdSessions || [];
  18022. if (countEl) countEl.innerText = list.length;
  18023. tbody.innerHTML = list.map((s, idx) => {
  18024. const isUp = (s.state || '').toLowerCase() === 'up';
  18025. const stateBadge = isUp
  18026. ? '<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>'
  18027. : `<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>`;
  18028. return `
  18029. <tr class="hover:bg-[#1a2636] text-slate-300">
  18030. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18031. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18032. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18033. <td class="py-1.5 px-3">${stateBadge}</td>
  18034. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18035. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18036. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18037. </tr>
  18038. `;
  18039. }).join('');
  18040. }
  18041. function openBfdInterfaceModal() {
  18042. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18043. document.getElementById('modal-bfd-iface-id').value = '';
  18044. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18045. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18046. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18047. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18048. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18049. document.getElementById('modal-bfd-iface-comment').value = '';
  18050. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18051. document.getElementById('modal-bfd-iface-passive').checked = false;
  18052. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18053. }
  18054. function openEditBfdInterfaceModal(id) {
  18055. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18056. if (!iface) return;
  18057. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18058. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18059. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18060. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18061. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18062. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18063. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18064. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18065. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18066. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18067. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18068. }
  18069. function closeBfdInterfaceModal() {
  18070. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18071. }
  18072. async function submitBfdInterface(e) {
  18073. e.preventDefault();
  18074. const id = document.getElementById('modal-bfd-iface-id').value;
  18075. const payload = {
  18076. id: id || undefined,
  18077. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18078. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18079. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18080. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18081. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18082. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18083. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18084. passive: document.getElementById('modal-bfd-iface-passive').checked
  18085. };
  18086. try {
  18087. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18088. method: 'POST',
  18089. headers: { 'Content-Type': 'application/json' },
  18090. body: JSON.stringify(payload)
  18091. });
  18092. if (!res.ok) throw new Error(await res.text());
  18093. closeBfdInterfaceModal();
  18094. showToast('Saved', `BFD profile saved`, 'success');
  18095. await loadDynamicRouting(false);
  18096. } catch (err) {
  18097. showToast('Error', err.message, 'error');
  18098. }
  18099. }
  18100. async function enableSelectedBfdInterface() {
  18101. const id = state.selectedBfdRow?.interfaces;
  18102. if (!id) return;
  18103. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18104. await loadDynamicRouting(false);
  18105. }
  18106. async function disableSelectedBfdInterface() {
  18107. const id = state.selectedBfdRow?.interfaces;
  18108. if (!id) return;
  18109. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18110. await loadDynamicRouting(false);
  18111. }
  18112. async function removeSelectedBfdInterface() {
  18113. const id = state.selectedBfdRow?.interfaces;
  18114. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18115. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18116. state.selectedBfdRow.interfaces = null;
  18117. await loadDynamicRouting(false);
  18118. }
  18119. function openBfdPeerModal() {
  18120. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18121. document.getElementById('modal-bfd-peer-id').value = '';
  18122. document.getElementById('modal-bfd-peer-address').value = '';
  18123. document.getElementById('modal-bfd-peer-interface').value = '';
  18124. document.getElementById('modal-bfd-peer-comment').value = '';
  18125. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18126. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18127. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18128. }
  18129. function openEditBfdPeerModal(id) {
  18130. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18131. if (!p) return;
  18132. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18133. document.getElementById('modal-bfd-peer-id').value = p.id;
  18134. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18135. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18136. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18137. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18138. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18139. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18140. }
  18141. function closeBfdPeerModal() {
  18142. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18143. }
  18144. async function submitBfdPeer(e) {
  18145. e.preventDefault();
  18146. const id = document.getElementById('modal-bfd-peer-id').value;
  18147. const payload = {
  18148. id: id || undefined,
  18149. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18150. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18151. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18152. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18153. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18154. };
  18155. try {
  18156. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18157. method: 'POST',
  18158. headers: { 'Content-Type': 'application/json' },
  18159. body: JSON.stringify(payload)
  18160. });
  18161. if (!res.ok) throw new Error(await res.text());
  18162. closeBfdPeerModal();
  18163. showToast('Saved', `BFD peer saved`, 'success');
  18164. await loadDynamicRouting(false);
  18165. } catch (err) {
  18166. showToast('Error', err.message, 'error');
  18167. }
  18168. }
  18169. async function enableSelectedBfdPeer() {
  18170. const id = state.selectedBfdRow?.peers;
  18171. if (!id) return;
  18172. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18173. if (!p) return;
  18174. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18175. await loadDynamicRouting(false);
  18176. }
  18177. async function disableSelectedBfdPeer() {
  18178. const id = state.selectedBfdRow?.peers;
  18179. if (!id) return;
  18180. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18181. if (!p) return;
  18182. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18183. await loadDynamicRouting(false);
  18184. }
  18185. async function removeSelectedBfdPeer() {
  18186. const id = state.selectedBfdRow?.peers;
  18187. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18188. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18189. state.selectedBfdRow.peers = null;
  18190. await loadDynamicRouting(false);
  18191. }
  18192. // ==============================================================================
  18193. // DYNAMIC ROUTING: BABEL MODULE
  18194. // ==============================================================================
  18195. state.babelInstances = [];
  18196. state.babelInterfaces = [];
  18197. state.babelNeighbors = [];
  18198. state.babelRoutes = [];
  18199. state.selectedBabelRow = {};
  18200. state.activeBabelTab = 'instances';
  18201. function switchBabelTab(tab) {
  18202. state.activeBabelTab = tab;
  18203. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  18204. const pane = document.getElementById(`babel-pane-${t}`);
  18205. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18206. if (pane) {
  18207. if (t === tab) pane.classList.remove('hidden');
  18208. else pane.classList.add('hidden');
  18209. }
  18210. if (btn) {
  18211. if (t === tab) {
  18212. 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';
  18213. } else {
  18214. 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';
  18215. }
  18216. }
  18217. });
  18218. }
  18219. function selectBabelRow(tab, id) {
  18220. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18221. state.selectedBabelRow[tab] = id;
  18222. if (tab === 'instances') {
  18223. renderBabelInstances();
  18224. const btnEn = document.getElementById('btn-babel-inst-enable');
  18225. const btnDis = document.getElementById('btn-babel-inst-disable');
  18226. const btnRem = document.getElementById('btn-babel-inst-remove');
  18227. if (btnEn) btnEn.disabled = false;
  18228. if (btnDis) btnDis.disabled = false;
  18229. if (btnRem) btnRem.disabled = false;
  18230. } else if (tab === 'interfaces') {
  18231. renderBabelInterfaces();
  18232. const btnEn = document.getElementById('btn-babel-iface-enable');
  18233. const btnDis = document.getElementById('btn-babel-iface-disable');
  18234. const btnRem = document.getElementById('btn-babel-iface-remove');
  18235. if (btnEn) btnEn.disabled = false;
  18236. if (btnDis) btnDis.disabled = false;
  18237. if (btnRem) btnRem.disabled = false;
  18238. }
  18239. }
  18240. function renderBabelInstances() {
  18241. const tbody = document.getElementById('babel-instances-table-body');
  18242. if (!tbody) return;
  18243. const countEl = document.getElementById('babel-instances-footer-count');
  18244. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18245. let list = state.babelInstances || [];
  18246. if (filter) {
  18247. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18248. }
  18249. if (countEl) countEl.innerText = list.length;
  18250. const selId = state.selectedBabelRow?.instances;
  18251. tbody.innerHTML = list.map((inst, idx) => {
  18252. const isSel = inst.id === selId;
  18253. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18254. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18255. const redist = [];
  18256. if (inst.redistribute_connected) redist.push('conn');
  18257. if (inst.redistribute_static) redist.push('static');
  18258. if (inst.redistribute_bgp) redist.push('bgp');
  18259. if (inst.redistribute_ospf) redist.push('ospf');
  18260. if (inst.redistribute_default) redist.push('default');
  18261. return `
  18262. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18263. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18264. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18265. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18266. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18267. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18268. </td>
  18269. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18270. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18271. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18272. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18273. </tr>
  18274. `;
  18275. }).join('');
  18276. }
  18277. function renderBabelInterfaces() {
  18278. const tbody = document.getElementById('babel-interfaces-table-body');
  18279. if (!tbody) return;
  18280. const countEl = document.getElementById('babel-interfaces-footer-count');
  18281. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18282. let list = state.babelInterfaces || [];
  18283. if (filter) {
  18284. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18285. }
  18286. if (countEl) countEl.innerText = list.length;
  18287. const selId = state.selectedBabelRow?.interfaces;
  18288. tbody.innerHTML = list.map((iface, idx) => {
  18289. const isSel = iface.id === selId;
  18290. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18291. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18292. return `
  18293. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18294. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18295. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18296. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18297. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18298. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18299. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18300. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18301. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18302. </tr>
  18303. `;
  18304. }).join('');
  18305. }
  18306. function renderBabelNeighbors() {
  18307. const tbody = document.getElementById('babel-neighbors-table-body');
  18308. if (!tbody) return;
  18309. const countEl = document.getElementById('babel-neighbors-footer-count');
  18310. const list = state.babelNeighbors || [];
  18311. if (countEl) countEl.innerText = list.length;
  18312. tbody.innerHTML = list.map((nbr, idx) => `
  18313. <tr class="hover:bg-[#1a2636] text-slate-300">
  18314. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18315. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18316. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18317. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18318. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || 0}</td>
  18319. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  18320. </tr>
  18321. `).join('');
  18322. }
  18323. function renderBabelRoutes() {
  18324. const tbody = document.getElementById('babel-routes-table-body');
  18325. if (!tbody) return;
  18326. const countEl = document.getElementById('babel-routes-footer-count');
  18327. const list = state.babelRoutes || [];
  18328. if (countEl) countEl.innerText = list.length;
  18329. tbody.innerHTML = list.map((r, idx) => `
  18330. <tr class="hover:bg-[#1a2636] text-slate-300">
  18331. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18332. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18333. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18334. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18335. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18336. </tr>
  18337. `).join('');
  18338. }
  18339. function openBabelInstanceModal() {
  18340. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18341. document.getElementById('modal-babel-instance-id').value = '';
  18342. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18343. document.getElementById('modal-babel-instance-routerid').value = '';
  18344. document.getElementById('modal-babel-instance-metric').value = '10';
  18345. document.getElementById('modal-babel-instance-comment').value = '';
  18346. document.getElementById('modal-babel-instance-enabled').checked = true;
  18347. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18348. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18349. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18350. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18351. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18352. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18353. }
  18354. function openEditBabelInstanceModal(id) {
  18355. const inst = (state.babelInstances || []).find(i => i.id === id);
  18356. if (!inst) return;
  18357. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18358. document.getElementById('modal-babel-instance-id').value = inst.id;
  18359. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18360. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18361. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18362. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18363. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18364. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18365. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18366. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18367. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18368. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18369. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18370. }
  18371. function closeBabelInstanceModal() {
  18372. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18373. }
  18374. async function submitBabelInstance(e) {
  18375. e.preventDefault();
  18376. const id = document.getElementById('modal-babel-instance-id').value;
  18377. const payload = {
  18378. id: id || undefined,
  18379. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18380. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18381. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18382. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18383. disabled: !document.getElementById('modal-babel-instance-enabled').checked,
  18384. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18385. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18386. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18387. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18388. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18389. };
  18390. try {
  18391. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18392. method: 'POST',
  18393. headers: { 'Content-Type': 'application/json' },
  18394. body: JSON.stringify(payload)
  18395. });
  18396. if (!res.ok) throw new Error(await res.text());
  18397. closeBabelInstanceModal();
  18398. showToast('Saved', `Babel instance saved`, 'success');
  18399. await loadDynamicRouting(false);
  18400. } catch (err) {
  18401. showToast('Error', err.message, 'error');
  18402. }
  18403. }
  18404. async function enableSelectedBabelInstance() {
  18405. const id = state.selectedBabelRow?.instances;
  18406. if (!id) return;
  18407. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18408. await loadDynamicRouting(false);
  18409. }
  18410. async function disableSelectedBabelInstance() {
  18411. const id = state.selectedBabelRow?.instances;
  18412. if (!id) return;
  18413. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18414. await loadDynamicRouting(false);
  18415. }
  18416. async function removeSelectedBabelInstance() {
  18417. const id = state.selectedBabelRow?.instances;
  18418. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18419. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18420. state.selectedBabelRow.instances = null;
  18421. await loadDynamicRouting(false);
  18422. }
  18423. function openBabelInterfaceModal() {
  18424. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface';
  18425. document.getElementById('modal-babel-iface-id').value = '';
  18426. document.getElementById('modal-babel-iface-pattern').value = '';
  18427. document.getElementById('modal-babel-iface-type').value = 'wired';
  18428. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18429. document.getElementById('modal-babel-iface-hello').value = '4';
  18430. document.getElementById('modal-babel-iface-update').value = '16';
  18431. document.getElementById('modal-babel-iface-comment').value = '';
  18432. document.getElementById('modal-babel-iface-enabled').checked = true;
  18433. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18434. }
  18435. function openEditBabelInterfaceModal(id) {
  18436. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18437. if (!iface) return;
  18438. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18439. document.getElementById('modal-babel-iface-id').value = iface.id;
  18440. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18441. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18442. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18443. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18444. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18445. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18446. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18447. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18448. }
  18449. function closeBabelInterfaceModal() {
  18450. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18451. }
  18452. async function submitBabelInterface(e) {
  18453. e.preventDefault();
  18454. const id = document.getElementById('modal-babel-iface-id').value;
  18455. const payload = {
  18456. id: id || undefined,
  18457. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18458. type: document.getElementById('modal-babel-iface-type').value,
  18459. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18460. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18461. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18462. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18463. disabled: !document.getElementById('modal-babel-iface-enabled').checked
  18464. };
  18465. try {
  18466. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18467. method: 'POST',
  18468. headers: { 'Content-Type': 'application/json' },
  18469. body: JSON.stringify(payload)
  18470. });
  18471. if (!res.ok) throw new Error(await res.text());
  18472. closeBabelInterfaceModal();
  18473. showToast('Saved', `Babel interface template saved`, 'success');
  18474. await loadDynamicRouting(false);
  18475. } catch (err) {
  18476. showToast('Error', err.message, 'error');
  18477. }
  18478. }
  18479. async function enableSelectedBabelInterface() {
  18480. const id = state.selectedBabelRow?.interfaces;
  18481. if (!id) return;
  18482. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18483. await loadDynamicRouting(false);
  18484. }
  18485. async function disableSelectedBabelInterface() {
  18486. const id = state.selectedBabelRow?.interfaces;
  18487. if (!id) return;
  18488. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18489. await loadDynamicRouting(false);
  18490. }
  18491. async function removeSelectedBabelInterface() {
  18492. const id = state.selectedBabelRow?.interfaces;
  18493. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18494. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18495. state.selectedBabelRow.interfaces = null;
  18496. await loadDynamicRouting(false);
  18497. }
  18498. // ==============================================================================
  18499. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18500. // ==============================================================================
  18501. state.radvInstances = [];
  18502. state.radvInterfaces = [];
  18503. state.selectedRadvRow = {};
  18504. state.activeRadvTab = 'instances';
  18505. function switchRadvTab(tab) {
  18506. state.activeRadvTab = tab;
  18507. ['instances', 'interfaces'].forEach(t => {
  18508. const pane = document.getElementById(`radv-pane-${t}`);
  18509. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18510. if (pane) {
  18511. if (t === tab) pane.classList.remove('hidden');
  18512. else pane.classList.add('hidden');
  18513. }
  18514. if (btn) {
  18515. if (t === tab) {
  18516. 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';
  18517. } else {
  18518. 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';
  18519. }
  18520. }
  18521. });
  18522. }
  18523. function selectRadvRow(tab, id) {
  18524. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18525. state.selectedRadvRow[tab] = id;
  18526. if (tab === 'instances') {
  18527. renderRAdvInstances();
  18528. const btnEn = document.getElementById('btn-radv-inst-enable');
  18529. const btnDis = document.getElementById('btn-radv-inst-disable');
  18530. const btnRem = document.getElementById('btn-radv-inst-remove');
  18531. if (btnEn) btnEn.disabled = false;
  18532. if (btnDis) btnDis.disabled = false;
  18533. if (btnRem) btnRem.disabled = false;
  18534. } else if (tab === 'interfaces') {
  18535. renderRAdvInterfaces();
  18536. const btnEn = document.getElementById('btn-radv-iface-enable');
  18537. const btnDis = document.getElementById('btn-radv-iface-disable');
  18538. const btnRem = document.getElementById('btn-radv-iface-remove');
  18539. if (btnEn) btnEn.disabled = false;
  18540. if (btnDis) btnDis.disabled = false;
  18541. if (btnRem) btnRem.disabled = false;
  18542. }
  18543. }
  18544. function renderRAdvInstances() {
  18545. const tbody = document.getElementById('radv-instances-table-body');
  18546. if (!tbody) return;
  18547. const countEl = document.getElementById('radv-instances-footer-count');
  18548. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18549. let list = state.radvInstances || [];
  18550. if (filter) {
  18551. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18552. }
  18553. if (countEl) countEl.innerText = list.length;
  18554. const selId = state.selectedRadvRow?.instances;
  18555. tbody.innerHTML = list.map((inst, idx) => {
  18556. const isSel = inst.id === selId;
  18557. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18558. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18559. return `
  18560. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18561. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18562. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18563. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18564. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18565. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18566. </td>
  18567. <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>
  18568. </tr>
  18569. `;
  18570. }).join('');
  18571. }
  18572. function renderRAdvInterfaces() {
  18573. const tbody = document.getElementById('radv-interfaces-table-body');
  18574. if (!tbody) return;
  18575. const countEl = document.getElementById('radv-interfaces-footer-count');
  18576. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18577. let list = state.radvInterfaces || [];
  18578. if (filter) {
  18579. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18580. }
  18581. if (countEl) countEl.innerText = list.length;
  18582. const selId = state.selectedRadvRow?.interfaces;
  18583. tbody.innerHTML = list.map((iface, idx) => {
  18584. const isSel = iface.id === selId;
  18585. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18586. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18587. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18588. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18589. return `
  18590. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18591. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18592. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18593. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18594. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18595. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18596. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18597. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18598. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18599. </tr>
  18600. `;
  18601. }).join('');
  18602. }
  18603. function openRAdvInstanceModal() {
  18604. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18605. document.getElementById('modal-radv-instance-id').value = '';
  18606. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18607. document.getElementById('modal-radv-instance-comment').value = '';
  18608. document.getElementById('modal-radv-instance-enabled').checked = true;
  18609. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18610. }
  18611. function openEditRAdvInstanceModal(id) {
  18612. const inst = (state.radvInstances || []).find(i => i.id === id);
  18613. if (!inst) return;
  18614. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18615. document.getElementById('modal-radv-instance-id').value = inst.id;
  18616. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18617. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18618. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18619. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18620. }
  18621. function closeRAdvInstanceModal() {
  18622. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18623. }
  18624. async function submitRAdvInstance(e) {
  18625. e.preventDefault();
  18626. const id = document.getElementById('modal-radv-instance-id').value;
  18627. const payload = {
  18628. id: id || undefined,
  18629. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18630. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18631. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18632. };
  18633. try {
  18634. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18635. method: 'POST',
  18636. headers: { 'Content-Type': 'application/json' },
  18637. body: JSON.stringify(payload)
  18638. });
  18639. if (!res.ok) throw new Error(await res.text());
  18640. closeRAdvInstanceModal();
  18641. showToast('Saved', `RAdv instance saved`, 'success');
  18642. await loadDynamicRouting(false);
  18643. } catch (err) {
  18644. showToast('Error', err.message, 'error');
  18645. }
  18646. }
  18647. async function enableSelectedRadvInstance() {
  18648. const id = state.selectedRadvRow?.instances;
  18649. if (!id) return;
  18650. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18651. await loadDynamicRouting(false);
  18652. }
  18653. async function disableSelectedRadvInstance() {
  18654. const id = state.selectedRadvRow?.instances;
  18655. if (!id) return;
  18656. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18657. await loadDynamicRouting(false);
  18658. }
  18659. async function removeSelectedRadvInstance() {
  18660. const id = state.selectedRadvRow?.instances;
  18661. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18662. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18663. state.selectedRadvRow.instances = null;
  18664. await loadDynamicRouting(false);
  18665. }
  18666. function openRAdvInterfaceModal() {
  18667. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18668. document.getElementById('modal-radv-iface-id').value = '';
  18669. document.getElementById('modal-radv-iface-interface').value = '';
  18670. document.getElementById('modal-radv-iface-instance').value = 'radv1';
  18671. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18672. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18673. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18674. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18675. document.getElementById('modal-radv-iface-prefixes').value = '';
  18676. document.getElementById('modal-radv-iface-rdnss').value = '';
  18677. document.getElementById('modal-radv-iface-comment').value = '';
  18678. document.getElementById('modal-radv-iface-enabled').checked = true;
  18679. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18680. }
  18681. function openEditRAdvInterfaceModal(id) {
  18682. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18683. if (!iface) return;
  18684. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18685. document.getElementById('modal-radv-iface-id').value = iface.id;
  18686. document.getElementById('modal-radv-iface-interface').value = iface.interface || '';
  18687. document.getElementById('modal-radv-iface-instance').value = iface.instance || '';
  18688. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18689. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18690. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18691. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18692. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18693. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18694. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18695. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18696. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18697. }
  18698. function closeRAdvInterfaceModal() {
  18699. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18700. }
  18701. async function submitRAdvInterface(e) {
  18702. e.preventDefault();
  18703. const id = document.getElementById('modal-radv-iface-id').value;
  18704. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18705. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18706. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18707. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18708. const payload = {
  18709. id: id || undefined,
  18710. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18711. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18712. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18713. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18714. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18715. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18716. prefixes: prefixes,
  18717. rdnss: rdnss,
  18718. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18719. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18720. };
  18721. try {
  18722. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18723. method: 'POST',
  18724. headers: { 'Content-Type': 'application/json' },
  18725. body: JSON.stringify(payload)
  18726. });
  18727. if (!res.ok) throw new Error(await res.text());
  18728. closeRAdvInterfaceModal();
  18729. showToast('Saved', `RAdv interface saved`, 'success');
  18730. await loadDynamicRouting(false);
  18731. } catch (err) {
  18732. showToast('Error', err.message, 'error');
  18733. }
  18734. }
  18735. async function enableSelectedRadvInterface() {
  18736. const id = state.selectedRadvRow?.interfaces;
  18737. if (!id) return;
  18738. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18739. await loadDynamicRouting(false);
  18740. }
  18741. async function disableSelectedRadvInterface() {
  18742. const id = state.selectedRadvRow?.interfaces;
  18743. if (!id) return;
  18744. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18745. await loadDynamicRouting(false);
  18746. }
  18747. async function removeSelectedRadvInterface() {
  18748. const id = state.selectedRadvRow?.interfaces;
  18749. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  18750. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  18751. state.selectedRadvRow.interfaces = null;
  18752. await loadDynamicRouting(false);
  18753. }