app.js 639 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. // Live polling every 2.5 seconds
  80. setInterval(() => {
  81. if (state.isPolling) {
  82. fetchData(false);
  83. }
  84. }, 2500);
  85. });
  86. // Navigation Handler
  87. function navigate(tabName) {
  88. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  89. navigate('bgp');
  90. return;
  91. }
  92. if (tabName === 'vlans') {
  93. navigate('interfaces');
  94. return;
  95. }
  96. state.activeTab = tabName;
  97. window.location.hash = tabName;
  98. // Update nav links styling
  99. document.querySelectorAll('.nav-link').forEach(link => {
  100. 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';
  101. });
  102. const activeNav = document.getElementById(`nav-${tabName}`);
  103. if (activeNav) {
  104. 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';
  105. }
  106. // Update page headers
  107. const titles = {
  108. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  109. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  110. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  111. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  112. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  113. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  114. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  115. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  116. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  117. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  118. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  119. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  120. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  121. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  122. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  123. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  124. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  125. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  126. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  127. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  128. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  129. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  130. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  131. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  132. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  133. };
  134. const header = titles[tabName] || titles.dashboard;
  135. const pTitle = document.getElementById('page-title');
  136. if (pTitle) pTitle.innerText = header.title;
  137. const pSub = document.getElementById('page-subtitle');
  138. if (pSub) pSub.innerText = header.sub;
  139. // Toggle sections dynamically for all section elements
  140. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  141. if (el.id === `section-${tabName}`) {
  142. el.classList.remove('hidden');
  143. } else {
  144. el.classList.add('hidden');
  145. }
  146. });
  147. if (tabName === 'bridge') loadBridge();
  148. if (tabName === 'firewall') loadFirewall();
  149. if (tabName === 'routes') loadRoutes();
  150. if (tabName === 'bgp') {
  151. loadDynamicRouting();
  152. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  153. }
  154. if (tabName === 'ospf') {
  155. loadDynamicRouting();
  156. switchOspfTab(state.activeOspfTab || 'instances');
  157. }
  158. if (tabName === 'routing-filters') loadDynamicRouting();
  159. if (tabName === 'dynamic-routing') loadDynamicRouting();
  160. if (tabName === 'ppp') loadPPP();
  161. if (tabName === 'eoip') loadEoIP();
  162. if (tabName === 'aerotun') loadAeroTUN();
  163. if (tabName === 'persistence') loadDebianConfig();
  164. if (tabName === 'pppoe') loadPPPoE();
  165. if (tabName === 'wireguard') loadWireGuard();
  166. if (tabName === 'ipsec') loadIPSec();
  167. if (tabName === 'l2tp') loadL2TP();
  168. if (tabName === 'pptp') loadPPTP();
  169. if (tabName === 'tools') loadToolsView();
  170. if (tabName === 'dhcp-client') loadDHCPClients();
  171. if (tabName === 'dhcp-server') loadDHCPServer();
  172. if (tabName === 'vrrp') loadVRRP();
  173. if (tabName === 'bwtest') loadBwTestView();
  174. if (tabName === 'settings') loadSettingsData();
  175. setTimeout(initTableSorting, 50);
  176. }
  177. // Fetch all core system, network and VPN telemetry
  178. async function fetchData(isManual = false) {
  179. const spinner = document.getElementById('refresh-spinner');
  180. if (isManual && spinner) spinner.classList.add('animate-spin');
  181. try {
  182. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  183. fetch(`${API_BASE}/system/status`),
  184. fetch(`${API_BASE}/interfaces`),
  185. fetch(`${API_BASE}/vlans`),
  186. fetch(`${API_BASE}/vpn/status`),
  187. fetch(`${API_BASE}/firewall/summary`),
  188. fetch(`${API_BASE}/routing/dynamic/summary`),
  189. fetch(`${API_BASE}/bridge/summary`),
  190. fetch(`${API_BASE}/dhcp/clients/summary`),
  191. fetch(`${API_BASE}/dhcp/clients`),
  192. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  193. ]);
  194. if (vrrpSumRes && vrrpSumRes.ok) {
  195. state.vrrpSummary = await vrrpSumRes.json();
  196. renderVRRPSummary();
  197. }
  198. if (dhcpSumRes && dhcpSumRes.ok) {
  199. state.dhcpSummary = await dhcpSumRes.json();
  200. const bDhcp = document.getElementById('badge-dhcp-client-count');
  201. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  202. }
  203. if (dhcpClientsRes && dhcpClientsRes.ok) {
  204. state.dhcpClients = await dhcpClientsRes.json();
  205. }
  206. if (brSummaryRes.ok) {
  207. state.bridgeSummary = await brSummaryRes.json();
  208. const bBridge = document.getElementById('badge-bridge-count');
  209. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  210. const sBr = document.getElementById('bridge-stat-bridges');
  211. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  212. const sPorts = document.getElementById('bridge-stat-ports');
  213. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  214. const sHosts = document.getElementById('bridge-stat-hosts');
  215. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  216. }
  217. if (statusRes.ok) state.systemStatus = await statusRes.json();
  218. if (ifacesRes.ok) {
  219. const ifacesData = await ifacesRes.json();
  220. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  221. state.interfaces = rawIfaces.filter(i => {
  222. if (!i.name) return false;
  223. if (i.name.startsWith('ep_')) return false;
  224. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  225. });
  226. try { populateToolsInterfaces(); } catch (e) {}
  227. }
  228. if (vlansRes.ok) {
  229. const vlansData = await vlansRes.json();
  230. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  231. }
  232. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  233. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  234. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  235. updateSystemMetrics();
  236. updateBadges();
  237. if (state.activeTab === 'dashboard') renderDashboard();
  238. if (state.activeTab === 'interfaces') renderInterfacesList();
  239. if (state.activeTab === 'vlans') renderVlansList();
  240. if (state.activeTab === 'firewall') loadFirewall(false);
  241. if (state.activeTab === 'routes') loadRoutes(false);
  242. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  243. if (state.activeTab === 'ppp') loadPPP(false);
  244. if (state.activeTab === 'eoip') loadEoIP(false);
  245. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  246. if (state.activeTab === 'pppoe') loadPPPoE(false);
  247. if (state.activeTab === 'wireguard') loadWireGuard(false);
  248. if (state.activeTab === 'ipsec') loadIPSec(false);
  249. if (state.activeTab === 'l2tp') loadL2TP(false);
  250. if (state.activeTab === 'pptp') loadPPTP(false);
  251. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  252. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  253. if (state.activeTab === 'vrrp') loadVRRP(false);
  254. if (state.activeTab === 'settings') loadSettingsData(false);
  255. fetchBwTestServerStatus();
  256. } catch (err) {
  257. console.error('Failed to fetch router state:', err);
  258. } finally {
  259. if (isManual && spinner) {
  260. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  261. }
  262. }
  263. }
  264. // Update Top KPI and Sidebar Telemetry
  265. function updateSystemMetrics() {
  266. const s = state.systemStatus;
  267. const v = state.vpnStatus;
  268. if (!s) return;
  269. // Sidebar Host & Uptime
  270. const sideHost = document.getElementById('side-hostname');
  271. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  272. const sideUp = document.getElementById('side-uptime');
  273. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  274. const sideGw = document.getElementById('side-gateway-ip');
  275. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  276. // Compute CPU Metrics
  277. let cpuPct = 0;
  278. if (s.cpu_pct !== undefined) {
  279. cpuPct = s.cpu_pct;
  280. } else if (s.cpu_load && s.cpu_load.length > 0) {
  281. const cores = s.cpu_cores || 1;
  282. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  283. }
  284. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  285. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  286. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  287. // Sidebar CPU
  288. const sideCpuVal = document.getElementById('side-cpu-val');
  289. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  290. const sideCpuBar = document.getElementById('side-cpu-bar');
  291. if (sideCpuBar) {
  292. sideCpuBar.style.width = cpuWidth;
  293. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  294. }
  295. // Dashboard CPU Card
  296. const dashCpuVal = document.getElementById('dash-cpu-val');
  297. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  298. const dashCpuBar = document.getElementById('dash-cpu-bar');
  299. if (dashCpuBar) {
  300. dashCpuBar.style.width = cpuWidth;
  301. if (cpuPct > 85) {
  302. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  303. } else if (cpuPct > 65) {
  304. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  305. } else {
  306. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  307. }
  308. }
  309. const dashCpuCores = document.getElementById('dash-cpu-cores');
  310. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  311. const dashCpuLoad = document.getElementById('dash-cpu-load');
  312. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  313. const dashCpuStatus = document.getElementById('dash-cpu-status');
  314. if (dashCpuStatus) {
  315. if (cpuPct > 85) {
  316. dashCpuStatus.innerText = 'High';
  317. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  318. } else if (cpuPct > 65) {
  319. dashCpuStatus.innerText = 'Heavy';
  320. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  321. } else {
  322. dashCpuStatus.innerText = 'Normal';
  323. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  324. }
  325. }
  326. // Compute RAM Metrics
  327. const memPct = Math.round(s.mem_usage_pct || 0);
  328. const memPctStr = `${memPct}%`;
  329. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  330. const usedMB = s.mem_used_mb || 0;
  331. const totalMB = s.mem_total_mb || 0;
  332. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  333. function fmtMemMB(mb) {
  334. if (mb >= 1024) {
  335. return `${(mb / 1024).toFixed(1)} GB`;
  336. }
  337. return `${mb} MB`;
  338. }
  339. // Sidebar RAM
  340. const sideRamVal = document.getElementById('side-ram-val');
  341. if (sideRamVal) sideRamVal.innerText = memPctStr;
  342. const sideRamBar = document.getElementById('side-ram-bar');
  343. if (sideRamBar) sideRamBar.style.width = memWidth;
  344. // Dashboard RAM Card
  345. const dashRamVal = document.getElementById('dash-ram-val');
  346. if (dashRamVal) dashRamVal.innerText = memPctStr;
  347. const dashRamBar = document.getElementById('dash-ram-bar');
  348. if (dashRamBar) {
  349. dashRamBar.style.width = memWidth;
  350. if (memPct > 85) {
  351. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  352. } else if (memPct > 70) {
  353. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  354. } else {
  355. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  356. }
  357. }
  358. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  359. if (dashRamUsedTotal) {
  360. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  361. }
  362. const dashRamFree = document.getElementById('dash-ram-free');
  363. if (dashRamFree) {
  364. dashRamFree.innerText = fmtMemMB(freeMB);
  365. }
  366. const dashRamStatus = document.getElementById('dash-ram-status');
  367. if (dashRamStatus) {
  368. if (memPct > 85) {
  369. dashRamStatus.innerText = 'High';
  370. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  371. } else {
  372. dashRamStatus.innerText = 'Active';
  373. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  374. }
  375. }
  376. // Legacy Dashboard Stats (Safe checks)
  377. const elIfacesUp = document.getElementById('stat-ifaces-up');
  378. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  379. const elIfacesTot = document.getElementById('stat-ifaces-total');
  380. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  381. const elIfacesDown = document.getElementById('stat-ifaces-down');
  382. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  383. const elVlans = document.getElementById('stat-vlans-count');
  384. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  385. // VPN Status Indicators
  386. if (v) {
  387. const totalActive = v.total_active_tunnels || 0;
  388. const statVpnActive = document.getElementById('stat-vpn-active');
  389. if (statVpnActive) statVpnActive.innerText = totalActive;
  390. const tunnelsDot = document.getElementById('tunnels-dot');
  391. const tunnelsLabel = document.getElementById('tunnels-label');
  392. if (tunnelsDot && tunnelsLabel) {
  393. if (totalActive > 0) {
  394. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  395. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  396. } else {
  397. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  398. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  399. }
  400. }
  401. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  402. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  403. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  404. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  405. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  406. }
  407. // Total Live Bandwidth Rate
  408. let totalRx = 0;
  409. let totalTx = 0;
  410. (state.interfaces || []).forEach(i => {
  411. if (i.rate) {
  412. totalRx += i.rate.rx_bytes_sec || 0;
  413. totalTx += i.rate.tx_bytes_sec || 0;
  414. }
  415. });
  416. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  417. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  418. }
  419. function setDotBadge(id, active) {
  420. const el = document.getElementById(id);
  421. if (!el) return;
  422. if (active) {
  423. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  424. } else {
  425. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  426. }
  427. }
  428. function updateBadges() {
  429. const bIfaces = document.getElementById('badge-ifaces-count');
  430. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  431. const bVlans = document.getElementById('badge-vlans-count');
  432. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  433. if (state.fwSummary) {
  434. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  435. const badgeFw = document.getElementById('badge-firewall-count');
  436. if (badgeFw) badgeFw.innerText = totalFwRules;
  437. }
  438. if (state.vpnStatus) {
  439. const v = state.vpnStatus;
  440. const bEoIP = document.getElementById('badge-eoip-count');
  441. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  442. const bAero = document.getElementById('badge-aerotun-count');
  443. if (bAero) bAero.innerText = v.total_aerotun || 0;
  444. const bPPPSess = document.getElementById('badge-ppp-sessions');
  445. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  446. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  447. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  448. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  449. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  450. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  451. }
  452. if (state.dynSummary) {
  453. const d = state.dynSummary;
  454. setDotBadge('badge-bgp-dot', d.bgp_running);
  455. setDotBadge('badge-ospf-dot', d.ospf_running);
  456. const bBgp = document.getElementById('badge-bgp-count');
  457. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  458. const bOspf = document.getElementById('badge-ospf-count');
  459. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  460. const bFilters = document.getElementById('badge-filters-count');
  461. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  462. }
  463. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  464. if (bDhcpServer) {
  465. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  466. }
  467. }
  468. // Render Dashboard View
  469. function renderDashboard() {
  470. const matrix = document.getElementById('port-matrix');
  471. matrix.innerHTML = '';
  472. (state.interfaces || []).forEach(iface => {
  473. const isUp = iface.state === 'UP';
  474. const isVlan = iface.is_vlan;
  475. const portCard = document.createElement('div');
  476. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  477. isUp
  478. ? (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')
  479. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  480. }`;
  481. portCard.onclick = () => openIfaceModal(iface.name);
  482. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  483. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  484. portCard.innerHTML = `
  485. <div class="flex items-center justify-between mb-2">
  486. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  487. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  488. </div>
  489. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  490. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  491. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  492. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  493. </div>
  494. `;
  495. matrix.appendChild(portCard);
  496. });
  497. const ifaceTbody = document.getElementById('quick-interfaces-table');
  498. if (ifaceTbody) {
  499. ifaceTbody.innerHTML = '';
  500. (state.interfaces || []).forEach(i => {
  501. const isUp = i.state === 'UP';
  502. const tr = document.createElement('tr');
  503. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  504. tr.onclick = () => openIfaceModal(i.name);
  505. const rxStr = i.rate?.rx_human || '0 B/s';
  506. const txStr = i.rate?.tx_human || '0 B/s';
  507. tr.innerHTML = `
  508. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  509. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  510. <span>${i.name}</span>
  511. </td>
  512. <td class="py-2.5 text-slate-300 font-sans">
  513. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  514. </td>
  515. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  516. <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>
  517. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  518. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  519. </td>
  520. <td class="py-2.5 text-right font-sans font-semibold">
  521. <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>
  522. </td>
  523. `;
  524. ifaceTbody.appendChild(tr);
  525. });
  526. }
  527. const vlanTbody = document.getElementById('quick-vlans-table');
  528. if (vlanTbody) {
  529. vlanTbody.innerHTML = '';
  530. }
  531. }
  532. // Expand / Collapse Handlers
  533. function toggleExpand(parentName) {
  534. if (state.expandedParents.has(parentName)) {
  535. state.expandedParents.delete(parentName);
  536. } else {
  537. state.expandedParents.add(parentName);
  538. }
  539. renderInterfacesList();
  540. }
  541. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  542. function supportsVLAN(iface) {
  543. if (!iface) return false;
  544. if (iface.is_vlan) return false;
  545. const name = (iface.name || '').toLowerCase();
  546. const type = (iface.type || '').toLowerCase();
  547. const role = (iface.role || '').toLowerCase();
  548. // Exclude loopback
  549. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  550. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  551. if (type === 'wireguard' || name.startsWith('wg')) return false;
  552. // Exclude PPP / PPPoE
  553. if (type === 'ppp' || name.startsWith('ppp')) return false;
  554. // Exclude other Layer 3 tunnels and dummy devices
  555. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  556. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  557. return false;
  558. }
  559. // If name already contains a dot, it's already a sub-interface
  560. if (name.includes('.')) return false;
  561. return true;
  562. }
  563. // Expand / Collapse Handlers
  564. function toggleExpand(parentName) {
  565. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  566. if (childVlans.length === 0) {
  567. // Cannot expand an interface with no VLANs
  568. state.expandedParents.delete(parentName);
  569. return;
  570. }
  571. if (state.expandedParents.has(parentName)) {
  572. state.expandedParents.delete(parentName);
  573. } else {
  574. state.expandedParents.add(parentName);
  575. }
  576. renderInterfacesList();
  577. }
  578. function expandAllIfaces(expand) {
  579. if (expand) {
  580. (state.interfaces || []).forEach(i => {
  581. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  582. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  583. });
  584. } else {
  585. state.expandedParents.clear();
  586. }
  587. renderInterfacesList();
  588. }
  589. // Filter and Render Hierarchical Interfaces List
  590. function filterIfaces(filter) {
  591. state.ifaceFilter = filter || 'all';
  592. renderInterfacesList();
  593. }
  594. function renderInterfacesList() {
  595. const tbody = document.getElementById('interfaces-tree-tbody');
  596. const emptyState = document.getElementById('interfaces-empty-state');
  597. const summary = document.getElementById('ifaces-list-summary');
  598. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  599. tbody.innerHTML = '';
  600. const allIfaces = state.interfaces || [];
  601. const allVlans = state.vlans || [];
  602. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  603. const filteredParents = parentIfaces.filter(parent => {
  604. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  605. if (query) {
  606. const matchName = parent.name.toLowerCase().includes(query);
  607. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  608. const matchRole = (parent.role || '').toLowerCase().includes(query);
  609. const matchType = (parent.type || '').toLowerCase().includes(query);
  610. const matchVlan = childVlans.some(v =>
  611. v.name.toLowerCase().includes(query) ||
  612. String(v.vlan_id).includes(query) ||
  613. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  614. (v.description || '').toLowerCase().includes(query)
  615. );
  616. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  617. }
  618. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  619. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  620. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  621. return true;
  622. });
  623. if (summary) {
  624. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  625. }
  626. if (filteredParents.length === 0) {
  627. emptyState?.classList.remove('hidden');
  628. return;
  629. }
  630. emptyState?.classList.add('hidden');
  631. filteredParents.forEach(parent => {
  632. const isUp = parent.state === 'UP';
  633. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  634. const hasVlans = childVlans.length > 0;
  635. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  636. const canHaveVlan = supportsVLAN(parent);
  637. const parentRow = document.createElement('tr');
  638. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  639. parentRow.innerHTML = `
  640. <td class="py-3 px-3 text-center">
  641. ${hasVlans ? `
  642. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  643. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  644. <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">
  645. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  646. </svg>
  647. </button>
  648. ` : `
  649. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  650. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  651. </div>
  652. `}
  653. </td>
  654. <td class="py-3 px-4">
  655. <div class="flex items-center space-x-2.5">
  656. <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">
  657. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  658. </div>
  659. <div>
  660. <div class="flex items-center gap-2">
  661. <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'}">
  662. <span>${parent.name}</span>
  663. <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>
  664. </span>
  665. ${hasVlans ? `
  666. <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>
  667. ` : `
  668. <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>
  669. `}
  670. </div>
  671. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  672. </div>
  673. </div>
  674. </td>
  675. <td class="py-3 px-4 font-sans">
  676. <div class="flex items-center gap-1.5">
  677. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  678. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  679. </div>
  680. </td>
  681. <td class="py-3 px-4">
  682. ${parent.ipv4 && parent.ipv4.length > 0
  683. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  684. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  685. }
  686. ${(() => {
  687. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  688. if (!c) return '';
  689. 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');
  690. 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>`;
  691. })()}
  692. </td>
  693. <td class="py-3 px-4 text-slate-400 text-[11px]">
  694. <div>${parent.mac || 'N/A'}</div>
  695. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  696. </td>
  697. <td class="py-3 px-4 text-[11px]">
  698. <div class="flex items-center space-x-2">
  699. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  700. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  701. </div>
  702. </td>
  703. <td class="py-3 px-4 font-sans">
  704. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  705. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  706. 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'
  707. }" title="Click to toggle link status">
  708. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  709. <span>${parent.state}</span>
  710. </button>
  711. </td>
  712. <td class="py-3 px-4 text-right space-x-2 font-sans">
  713. ${(() => {
  714. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  715. if (c) {
  716. 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>`;
  717. }
  718. 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>`;
  719. })()}
  720. ${canHaveVlan ? `
  721. <button onclick="openVlanModal('${parent.name}')"
  722. 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">
  723. + Add VLAN
  724. </button>
  725. ` : ''}
  726. <button onclick="openIfaceModal('${parent.name}')"
  727. 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">
  728. Configure
  729. </button>
  730. </td>
  731. `;
  732. tbody.appendChild(parentRow);
  733. if (isExpanded) {
  734. const drawerRow = document.createElement('tr');
  735. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  736. const drawerCell = document.createElement('td');
  737. drawerCell.colSpan = 8;
  738. drawerCell.className = 'p-0';
  739. drawerCell.innerHTML = `
  740. <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">
  741. <div class="flex items-center justify-between mb-3">
  742. <div class="flex items-center space-x-3">
  743. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  744. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  745. </span>
  746. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  747. ${childVlans.length} Attached
  748. </span>
  749. </div>
  750. <button onclick="openVlanModal('${parent.name}')"
  751. 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">
  752. <span>+ Create VLAN on ${parent.name}</span>
  753. </button>
  754. </div>
  755. ${childVlans.length === 0 ? `
  756. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  757. <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>
  758. <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">
  759. <span>+ Create Your First VLAN on ${parent.name}</span>
  760. </button>
  761. </div>
  762. ` : `
  763. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  764. <table class="w-full text-left text-xs font-mono">
  765. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  766. <tr>
  767. <th class="py-2.5 px-4">VLAN ID</th>
  768. <th class="py-2.5 px-4">Interface Device</th>
  769. <th class="py-2.5 px-4">Subnet Gateway</th>
  770. <th class="py-2.5 px-4">Role / Alias</th>
  771. <th class="py-2.5 px-4">MTU</th>
  772. <th class="py-2.5 px-4">Throughput</th>
  773. <th class="py-2.5 px-4">Status</th>
  774. <th class="py-2.5 px-4 text-right">Actions</th>
  775. </tr>
  776. </thead>
  777. <tbody class="divide-y divide-slate-800/70">
  778. ${childVlans.map(v => {
  779. const isVlanUp = v.state === 'UP';
  780. return `
  781. <tr class="hover:bg-slate-800/40 transition">
  782. <td class="py-2.5 px-4">
  783. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  784. VLAN ${v.vlan_id}
  785. </span>
  786. </td>
  787. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  788. <span class="text-cyan-500">└─</span>
  789. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  790. <span>${v.name}</span>
  791. <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>
  792. </span>
  793. </td>
  794. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  795. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  796. ${(() => {
  797. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  798. if (!c) return '';
  799. 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';
  800. 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>`;
  801. })()}
  802. </td>
  803. <td class="py-2.5 px-4 font-sans text-slate-300">
  804. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  805. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  806. </td>
  807. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  808. <td class="py-2.5 px-4 text-[11px]">
  809. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  810. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  811. </td>
  812. <td class="py-2.5 px-4 font-sans">
  813. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  814. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  815. 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'
  816. }">
  817. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  818. <span>${v.state}</span>
  819. </button>
  820. </td>
  821. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  822. ${(() => {
  823. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  824. if (c) {
  825. 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>`;
  826. }
  827. 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>`;
  828. })()}
  829. <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>
  830. <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>
  831. </td>
  832. </tr>
  833. `;
  834. }).join('')}
  835. </tbody>
  836. </table>
  837. </div>
  838. `}
  839. </div>
  840. `;
  841. drawerRow.appendChild(drawerCell);
  842. tbody.appendChild(drawerRow);
  843. }
  844. });
  845. }
  846. // Render VLANs Dedicated View
  847. function renderVlansList() {
  848. const tbody = document.getElementById('vlans-table-body');
  849. if (!tbody) return;
  850. const emptyState = document.getElementById('vlans-empty-state');
  851. const countBadge = document.getElementById('vlans-table-count');
  852. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  853. tbody.innerHTML = '';
  854. const allVlans = state.vlans || [];
  855. if (countBadge) countBadge.innerText = allVlans.length;
  856. const filtered = allVlans.filter(v => {
  857. if (!query) return true;
  858. return v.name.toLowerCase().includes(query) ||
  859. String(v.vlan_id).includes(query) ||
  860. (v.description || '').toLowerCase().includes(query) ||
  861. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  862. });
  863. if (allVlans.length === 0) {
  864. emptyState.classList.remove('hidden');
  865. return;
  866. }
  867. emptyState.classList.add('hidden');
  868. filtered.forEach(v => {
  869. const isUp = v.state === 'UP';
  870. const tr = document.createElement('tr');
  871. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  872. tr.innerHTML = `
  873. <td class="py-3 px-4">
  874. <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">
  875. VLAN ${v.vlan_id}
  876. </span>
  877. </td>
  878. <td class="py-3 px-4 font-bold text-white">
  879. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  880. <span>${v.name}</span>
  881. <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>
  882. </span>
  883. </td>
  884. <td class="py-3 px-4 text-slate-300">
  885. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  886. </td>
  887. <td class="py-3 px-4 text-emerald-400 font-medium">
  888. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  889. </td>
  890. <td class="py-3 px-4 text-slate-300 font-sans">
  891. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  892. </td>
  893. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  894. <td class="py-3 px-4 font-sans">
  895. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  896. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  897. 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'
  898. }">
  899. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  900. <span>${v.state}</span>
  901. </button>
  902. </td>
  903. <td class="py-3 px-4 text-right space-x-2 font-sans">
  904. <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>
  905. <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>
  906. </td>
  907. `;
  908. tbody.appendChild(tr);
  909. });
  910. }
  911. // Toggle interface UP / DOWN
  912. async function toggleInterfaceState(name, newState) {
  913. try {
  914. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  915. method: 'POST',
  916. headers: { 'Content-Type': 'application/json' },
  917. body: JSON.stringify({ state: newState })
  918. });
  919. const data = await res.json();
  920. if (res.ok) {
  921. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  922. fetchData(false);
  923. } else {
  924. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  925. }
  926. } catch (err) {
  927. showToast('Error', err.message, 'error');
  928. }
  929. }
  930. // ---------------- MikroTik Flag & Utilities ----------------
  931. function renderMikroTikFlag(running, disabled) {
  932. if (running) {
  933. 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>`;
  934. }
  935. if (disabled) {
  936. 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>`;
  937. }
  938. 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>`;
  939. }
  940. function copyToClipboard(text, label = 'Text') {
  941. navigator.clipboard.writeText(text).then(() => {
  942. showToast('Copied', `${label} copied to clipboard`, 'success');
  943. }).catch(() => {
  944. prompt('Copy value:', text);
  945. });
  946. }
  947. // ======================== PPP Profiles Shared Helper ========================
  948. async function fetchPPPProfilesList() {
  949. try {
  950. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  951. if (res.ok) {
  952. state.pppProfiles = await res.json();
  953. }
  954. } catch (err) {
  955. console.error('Failed to load PPP profiles:', err);
  956. }
  957. }
  958. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  959. const sel = document.getElementById(selectId);
  960. if (!sel) return;
  961. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  962. { name: 'default', use_encryption: 'no' },
  963. { name: 'default-encryption', use_encryption: 'required' }
  964. ];
  965. sel.innerHTML = '';
  966. profiles.forEach(p => {
  967. const opt = document.createElement('option');
  968. opt.value = p.name;
  969. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  970. opt.innerText = `${p.name}${encBadge}`;
  971. sel.appendChild(opt);
  972. });
  973. if (selectedVal) {
  974. sel.value = selectedVal;
  975. } else {
  976. sel.value = defaultVal;
  977. }
  978. if (!sel.value && sel.options.length > 0) {
  979. sel.selectedIndex = 0;
  980. }
  981. }
  982. // ======================== PPPoE Multi-Instance ========================
  983. async function loadPPPoE(populateInputs = true) {
  984. try {
  985. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  986. await fetchPPPProfilesList();
  987. }
  988. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  989. const list = await res.json();
  990. state.pppoeList = Array.isArray(list) ? list : [];
  991. const badge = document.getElementById('pppoe-count-badge');
  992. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  993. const tbody = document.getElementById('pppoe-table-body');
  994. const empty = document.getElementById('pppoe-empty');
  995. if (!tbody) return;
  996. tbody.innerHTML = '';
  997. if (state.pppoeList.length === 0) {
  998. if (empty) empty.classList.remove('hidden');
  999. } else {
  1000. if (empty) empty.classList.add('hidden');
  1001. state.pppoeList.forEach(inst => {
  1002. const tr = document.createElement('tr');
  1003. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1004. tr.innerHTML = `
  1005. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1006. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1007. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1008. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1009. <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>
  1010. <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>
  1011. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1012. <td class="py-2.5 px-3 text-center">
  1013. <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'}">
  1014. ${inst.default_route ? 'Yes' : 'No'}
  1015. </span>
  1016. </td>
  1017. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1018. ${inst.running ? `
  1019. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1020. ` : `
  1021. <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>
  1022. `}
  1023. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1024. ${inst.disabled ? 'Enable' : 'Disable'}
  1025. </button>
  1026. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1027. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1028. </td>
  1029. `;
  1030. tbody.appendChild(tr);
  1031. });
  1032. }
  1033. } catch (err) {
  1034. console.error('Failed to load PPPoE:', err);
  1035. }
  1036. }
  1037. function openAddPPPoEModal() {
  1038. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1039. document.getElementById('pppoe-modal-edit-orig').value = '';
  1040. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1041. document.getElementById('pppoe-modal-name').readOnly = false;
  1042. document.getElementById('pppoe-modal-user').value = '';
  1043. document.getElementById('pppoe-modal-pass').value = '';
  1044. document.getElementById('pppoe-modal-service').value = '';
  1045. document.getElementById('pppoe-modal-mtu').value = '1492';
  1046. document.getElementById('pppoe-modal-defroute').checked = true;
  1047. document.getElementById('pppoe-modal-reconnect').checked = true;
  1048. document.getElementById('pppoe-modal-disabled').checked = false;
  1049. // Populate profiles
  1050. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1051. // Populate interfaces
  1052. const sel = document.getElementById('pppoe-modal-iface');
  1053. sel.innerHTML = '';
  1054. (state.interfaces || []).forEach(i => {
  1055. if (i.name === 'lo') return;
  1056. const opt = document.createElement('option');
  1057. opt.value = i.name;
  1058. opt.innerText = `${i.name} (${i.role || i.type})`;
  1059. sel.appendChild(opt);
  1060. });
  1061. document.getElementById('pppoe-modal').classList.remove('hidden');
  1062. }
  1063. function openEditPPPoEModal(name) {
  1064. const inst = (state.pppoeList || []).find(i => i.name === name);
  1065. if (!inst) return;
  1066. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1067. document.getElementById('pppoe-modal-edit-orig').value = name;
  1068. document.getElementById('pppoe-modal-name').value = inst.name;
  1069. document.getElementById('pppoe-modal-name').readOnly = true;
  1070. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1071. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1072. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1073. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1074. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1075. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1076. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1077. // Populate profiles
  1078. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1079. const sel = document.getElementById('pppoe-modal-iface');
  1080. sel.innerHTML = '';
  1081. (state.interfaces || []).forEach(i => {
  1082. if (i.name === 'lo') return;
  1083. const opt = document.createElement('option');
  1084. opt.value = i.name;
  1085. opt.innerText = `${i.name} (${i.role || i.type})`;
  1086. if (i.name === inst.interface) opt.selected = true;
  1087. sel.appendChild(opt);
  1088. });
  1089. document.getElementById('pppoe-modal').classList.remove('hidden');
  1090. }
  1091. function closePPPoEModal() {
  1092. document.getElementById('pppoe-modal').classList.add('hidden');
  1093. }
  1094. async function submitSavePPPoE(e) {
  1095. e.preventDefault();
  1096. const name = document.getElementById('pppoe-modal-name').value.trim();
  1097. const iface = document.getElementById('pppoe-modal-iface').value;
  1098. const user = document.getElementById('pppoe-modal-user').value.trim();
  1099. const pass = document.getElementById('pppoe-modal-pass').value;
  1100. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1101. const service = document.getElementById('pppoe-modal-service').value.trim();
  1102. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1103. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1104. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1105. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1106. try {
  1107. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1108. method: 'POST',
  1109. headers: { 'Content-Type': 'application/json' },
  1110. body: JSON.stringify({
  1111. name,
  1112. interface: iface,
  1113. username: user,
  1114. password: pass,
  1115. profile: profile,
  1116. service_name: service,
  1117. mtu,
  1118. default_route: defRoute,
  1119. auto_reconnect: reconnect,
  1120. disabled
  1121. })
  1122. });
  1123. if (res.ok) {
  1124. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1125. closePPPoEModal();
  1126. loadPPPoE(false);
  1127. fetchData(false);
  1128. } else {
  1129. const err = await res.json();
  1130. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. async function connectPPPoEInstance(name) {
  1137. try {
  1138. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1139. if (res.ok) {
  1140. showToast('Connecting', `Dialing ${name}...`, 'info');
  1141. setTimeout(() => loadPPPoE(false), 2000);
  1142. }
  1143. } catch (err) {
  1144. showToast('Error', err.message, 'error');
  1145. }
  1146. }
  1147. async function disconnectPPPoEInstance(name) {
  1148. try {
  1149. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1150. if (res.ok) {
  1151. showToast('Disconnected', `${name} session terminated`, 'info');
  1152. setTimeout(() => loadPPPoE(false), 1000);
  1153. }
  1154. } catch (err) {
  1155. showToast('Error', err.message, 'error');
  1156. }
  1157. }
  1158. async function togglePPPoEState(name, enable) {
  1159. try {
  1160. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1161. method: 'POST',
  1162. headers: { 'Content-Type': 'application/json' },
  1163. body: JSON.stringify({ enabled: enable })
  1164. });
  1165. if (res.ok) {
  1166. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1167. loadPPPoE(false);
  1168. }
  1169. } catch (err) {
  1170. showToast('Error', err.message, 'error');
  1171. }
  1172. }
  1173. async function deletePPPoEInstance(name) {
  1174. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1175. try {
  1176. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1177. if (res.ok) {
  1178. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1179. loadPPPoE(false);
  1180. fetchData(false);
  1181. }
  1182. } catch (err) {
  1183. showToast('Error', err.message, 'error');
  1184. }
  1185. }
  1186. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1187. state.wgSubTab = 'ifaces';
  1188. function switchWGSubTab(tab) {
  1189. state.wgSubTab = tab;
  1190. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1191. const peersPanel = document.getElementById('wg-subtab-peers');
  1192. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1193. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1194. if (tab === 'ifaces') {
  1195. ifacesPanel?.classList.remove('hidden');
  1196. peersPanel?.classList.add('hidden');
  1197. 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';
  1198. 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';
  1199. } else {
  1200. ifacesPanel?.classList.add('hidden');
  1201. peersPanel?.classList.remove('hidden');
  1202. 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';
  1203. 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';
  1204. renderWGPeers();
  1205. }
  1206. }
  1207. async function loadWireGuard(populateInputs = true) {
  1208. try {
  1209. const [ifacesRes, peersRes] = await Promise.all([
  1210. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1211. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1212. ]);
  1213. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1214. const peers = peersRes.ok ? await peersRes.json() : [];
  1215. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1216. state.wgPeers = Array.isArray(peers) ? peers : [];
  1217. // Badges
  1218. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1219. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1220. const peersCountBadge = document.getElementById('wg-peers-count');
  1221. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1222. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1223. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1224. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1225. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1226. // Render Interfaces
  1227. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1228. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1229. if (ifacesTbody) {
  1230. ifacesTbody.innerHTML = '';
  1231. if (state.wgInterfaces.length === 0) {
  1232. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1233. } else {
  1234. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1235. state.wgInterfaces.forEach(iface => {
  1236. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1237. const tr = document.createElement('tr');
  1238. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1239. tr.innerHTML = `
  1240. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1241. <td class="py-2.5 px-3">
  1242. <div class="flex items-center gap-1.5">
  1243. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1244. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1245. </div>
  1246. </td>
  1247. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1248. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1249. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1250. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1251. ${(iface.public_key || '').substring(0, 10)}... 📋
  1252. </span>
  1253. </td>
  1254. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1255. <td class="py-2.5 px-3 text-center">
  1256. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1257. </td>
  1258. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1259. ${iface.running ? `
  1260. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1261. ` : `
  1262. <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>
  1263. `}
  1264. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1265. ${iface.disabled ? 'Enable' : 'Disable'}
  1266. </button>
  1267. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1268. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1269. </td>
  1270. `;
  1271. ifacesTbody.appendChild(tr);
  1272. });
  1273. }
  1274. }
  1275. // Populate filter dropdown in peers tab
  1276. const filterSel = document.getElementById('wg-peers-filter-iface');
  1277. if (filterSel) {
  1278. const currentVal = filterSel.value;
  1279. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1280. state.wgInterfaces.forEach(i => {
  1281. const opt = document.createElement('option');
  1282. opt.value = i.name;
  1283. opt.innerText = i.name;
  1284. if (i.name === currentVal) opt.selected = true;
  1285. filterSel.appendChild(opt);
  1286. });
  1287. }
  1288. renderWGPeers();
  1289. } catch (err) {
  1290. console.error('Failed to load WireGuard:', err);
  1291. }
  1292. }
  1293. function formatWGPeerEndpoint(address, port) {
  1294. if (!address || address === '(none)') return '--';
  1295. let addr = address.trim();
  1296. let p = port || 0;
  1297. while (addr.includes(':') && !addr.startsWith('[')) {
  1298. const lastColon = addr.lastIndexOf(':');
  1299. const maybePort = addr.substring(lastColon + 1);
  1300. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1301. if (!p) p = parseInt(maybePort, 10);
  1302. addr = addr.substring(0, lastColon);
  1303. } else {
  1304. break;
  1305. }
  1306. }
  1307. return p ? `${addr}:${p}` : addr;
  1308. }
  1309. function renderWGPeers() {
  1310. const filterSel = document.getElementById('wg-peers-filter-iface');
  1311. const selectedIface = filterSel ? filterSel.value : '';
  1312. const tbody = document.getElementById('wg-peers-table-body');
  1313. const empty = document.getElementById('wg-peers-empty');
  1314. if (!tbody) return;
  1315. tbody.innerHTML = '';
  1316. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1317. if (filtered.length === 0) {
  1318. if (empty) empty.classList.remove('hidden');
  1319. } else {
  1320. if (empty) empty.classList.add('hidden');
  1321. filtered.forEach(p => {
  1322. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1323. const tr = document.createElement('tr');
  1324. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1325. tr.innerHTML = `
  1326. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1327. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1328. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1329. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1330. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1331. ${(p.public_key || '').substring(0, 10)}... 📋
  1332. </span>
  1333. </td>
  1334. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1335. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1336. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1337. <td class="py-2.5 px-3 font-mono text-[11px]">
  1338. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1339. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1340. </td>
  1341. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1342. <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">
  1343. ${p.disabled ? 'Enable' : 'Disable'}
  1344. </button>
  1345. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1346. <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>
  1347. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1348. </td>
  1349. `;
  1350. tbody.appendChild(tr);
  1351. });
  1352. }
  1353. }
  1354. function openAddWGInterfaceModal() {
  1355. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1356. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1357. const nameEl = document.getElementById('wg-iface-modal-name');
  1358. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1359. nameEl.readOnly = false;
  1360. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1361. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1362. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1363. document.getElementById('wg-iface-modal-comment').value = '';
  1364. document.getElementById('wg-iface-modal-pubkey').value = '';
  1365. document.getElementById('wg-iface-modal-privkey').value = '';
  1366. document.getElementById('wg-iface-modal-disabled').checked = false;
  1367. generateWGInterfaceKeys();
  1368. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1369. }
  1370. function openEditWGInterfaceModal(name) {
  1371. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1372. if (!iface) return;
  1373. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1374. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1375. const nameEl = document.getElementById('wg-iface-modal-name');
  1376. nameEl.value = iface.name;
  1377. nameEl.readOnly = false; // ALLOW RENAMING
  1378. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1379. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1380. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1381. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1382. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1383. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1384. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1385. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1386. }
  1387. function closeAddWGInterfaceModal() {
  1388. document.getElementById('wg-iface-modal').classList.add('hidden');
  1389. }
  1390. async function generateWGInterfaceKeys() {
  1391. try {
  1392. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1393. const keys = await res.json();
  1394. if (res.ok) {
  1395. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1396. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1397. }
  1398. } catch (err) {
  1399. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1400. }
  1401. }
  1402. async function onWGInterfacePrivKeyInput() {
  1403. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1404. if (!privKey) return;
  1405. try {
  1406. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1407. method: 'POST',
  1408. headers: { 'Content-Type': 'application/json' },
  1409. body: JSON.stringify({ private_key: privKey })
  1410. });
  1411. if (res.ok) {
  1412. const data = await res.json();
  1413. if (data.public_key) {
  1414. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1415. }
  1416. }
  1417. } catch (err) {
  1418. // Ignore while typing
  1419. }
  1420. }
  1421. function toggleWGPrivKeyVisibility() {
  1422. const el = document.getElementById('wg-iface-modal-privkey');
  1423. const btn = document.getElementById('btn-toggle-wg-privkey');
  1424. if (el.type === 'password') {
  1425. el.type = 'text';
  1426. btn.innerText = '🙈 Hide';
  1427. } else {
  1428. el.type = 'password';
  1429. btn.innerText = '👁️ Show';
  1430. }
  1431. }
  1432. function copyWGInterfacePubKey() {
  1433. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1434. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1435. }
  1436. async function submitSaveWGInterface(e) {
  1437. e.preventDefault();
  1438. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1439. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1440. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1441. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1442. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1443. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1444. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1445. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1446. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1447. try {
  1448. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1449. method: 'POST',
  1450. headers: { 'Content-Type': 'application/json' },
  1451. body: JSON.stringify({
  1452. orig_name: origName,
  1453. name,
  1454. listen_port: port,
  1455. address: addr,
  1456. mtu,
  1457. comment,
  1458. public_key: pub,
  1459. private_key: priv,
  1460. disabled
  1461. })
  1462. });
  1463. const data = await res.json();
  1464. if (res.ok) {
  1465. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1466. closeAddWGInterfaceModal();
  1467. loadWireGuard(false);
  1468. fetchData(false);
  1469. } else {
  1470. showToast('Error', data.error || 'Failed to save interface', 'error');
  1471. }
  1472. } catch (err) {
  1473. showToast('Error', err.message, 'error');
  1474. }
  1475. }
  1476. async function startWGInterface(name) {
  1477. try {
  1478. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1479. if (res.ok) {
  1480. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1481. loadWireGuard(false);
  1482. fetchData(false);
  1483. }
  1484. } catch (err) {
  1485. showToast('Error', err.message, 'error');
  1486. }
  1487. }
  1488. async function stopWGInterface(name) {
  1489. try {
  1490. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1491. if (res.ok) {
  1492. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1493. loadWireGuard(false);
  1494. fetchData(false);
  1495. }
  1496. } catch (err) {
  1497. showToast('Error', err.message, 'error');
  1498. }
  1499. }
  1500. async function toggleWGInterfaceState(name, enable) {
  1501. try {
  1502. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1503. method: 'POST',
  1504. headers: { 'Content-Type': 'application/json' },
  1505. body: JSON.stringify({ enabled: enable })
  1506. });
  1507. if (res.ok) {
  1508. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1509. loadWireGuard(false);
  1510. fetchData(false);
  1511. }
  1512. } catch (err) {
  1513. showToast('Error', err.message, 'error');
  1514. }
  1515. }
  1516. async function deleteWGInterface(name) {
  1517. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1518. try {
  1519. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1520. if (res.ok) {
  1521. showToast('Deleted', `Interface ${name} removed`, 'success');
  1522. loadWireGuard(false);
  1523. fetchData(false);
  1524. }
  1525. } catch (err) {
  1526. showToast('Error', err.message, 'error');
  1527. }
  1528. }
  1529. function populateWGPeerIfaceSelect(selectedIface = '') {
  1530. const sel = document.getElementById('wg-peer-modal-iface');
  1531. if (!sel) return;
  1532. sel.innerHTML = '';
  1533. (state.wgInterfaces || []).forEach(i => {
  1534. const opt = document.createElement('option');
  1535. opt.value = i.name;
  1536. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1537. if (i.name === selectedIface) opt.selected = true;
  1538. sel.appendChild(opt);
  1539. });
  1540. }
  1541. function openAddWGPeerModal() {
  1542. if ((state.wgInterfaces || []).length === 0) {
  1543. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1544. openAddWGInterfaceModal();
  1545. return;
  1546. }
  1547. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1548. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1549. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1550. populateWGPeerIfaceSelect();
  1551. document.getElementById('wg-peer-modal-name').value = '';
  1552. document.getElementById('wg-peer-modal-pubkey').value = '';
  1553. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1554. document.getElementById('wg-peer-modal-endpoint').value = '';
  1555. document.getElementById('wg-peer-modal-port').value = '';
  1556. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1557. document.getElementById('wg-peer-modal-preshared').value = '';
  1558. document.getElementById('wg-peer-modal-disabled').checked = false;
  1559. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1560. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1561. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1562. }
  1563. function openEditWGPeerModal(ifaceName, pubKey) {
  1564. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1565. if (!peer) {
  1566. showToast('Not Found', 'Peer not found', 'warning');
  1567. return;
  1568. }
  1569. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1570. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1571. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1572. populateWGPeerIfaceSelect(peer.interface);
  1573. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1574. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1575. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1576. let epHost = (peer.endpoint_address || '').trim();
  1577. let epPort = peer.endpoint_port || '';
  1578. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1579. const lastColon = epHost.lastIndexOf(':');
  1580. const maybePort = epHost.substring(lastColon + 1);
  1581. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1582. if (!epPort) epPort = parseInt(maybePort, 10);
  1583. epHost = epHost.substring(0, lastColon);
  1584. } else {
  1585. break;
  1586. }
  1587. }
  1588. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  1589. document.getElementById('wg-peer-modal-port').value = epPort;
  1590. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1591. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1592. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1593. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1594. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1595. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1596. }
  1597. function closeAddWGPeerModal() {
  1598. document.getElementById('wg-peer-modal').classList.add('hidden');
  1599. }
  1600. async function generatePeerKeypairHelper() {
  1601. try {
  1602. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1603. const keys = await res.json();
  1604. if (res.ok) {
  1605. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1606. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1607. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1608. checkWGPeerKeyValidity();
  1609. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1610. }
  1611. } catch (err) {
  1612. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1613. }
  1614. }
  1615. function copyGeneratedPeerPrivKey() {
  1616. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1617. if (priv) copyToClipboard(priv, 'Client Private Key');
  1618. }
  1619. async function generatePeerPSK() {
  1620. try {
  1621. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1622. const keys = await res.json();
  1623. if (res.ok && keys.private_key) {
  1624. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1625. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1626. }
  1627. } catch (err) {
  1628. showToast('Error', err.message, 'error');
  1629. }
  1630. }
  1631. function checkWGPeerKeyValidity() {
  1632. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1633. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1634. const warningEl = document.getElementById('wg-peer-key-warning');
  1635. if (!warningEl) return;
  1636. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1637. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1638. warningEl.classList.remove('hidden');
  1639. } else {
  1640. warningEl.classList.add('hidden');
  1641. }
  1642. }
  1643. async function submitSaveWGPeer(e) {
  1644. e.preventDefault();
  1645. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1646. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1647. const iface = document.getElementById('wg-peer-modal-iface').value;
  1648. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1649. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1650. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1651. .split(',')
  1652. .map(s => s.trim())
  1653. .filter(s => s.length > 0);
  1654. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1655. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1656. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1657. const lastColon = epHost.lastIndexOf(':');
  1658. const maybePort = epHost.substring(lastColon + 1);
  1659. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1660. if (!epPort) epPort = parseInt(maybePort, 10);
  1661. epHost = epHost.substring(0, lastColon);
  1662. } else {
  1663. break;
  1664. }
  1665. }
  1666. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1667. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1668. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1669. // Validation
  1670. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1671. if (targetIface && targetIface.public_key === pub) {
  1672. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1673. return;
  1674. }
  1675. try {
  1676. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1677. method: 'POST',
  1678. headers: { 'Content-Type': 'application/json' },
  1679. body: JSON.stringify({
  1680. orig_interface: origIface,
  1681. orig_public_key: origPubKey,
  1682. interface: iface,
  1683. name,
  1684. public_key: pub,
  1685. allowed_ips: allowed,
  1686. endpoint_address: epHost,
  1687. endpoint_port: epPort,
  1688. persistent_keepalive: keepalive,
  1689. preshared_key: psk,
  1690. disabled
  1691. })
  1692. });
  1693. const data = await res.json();
  1694. if (res.ok) {
  1695. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1696. closeAddWGPeerModal();
  1697. loadWireGuard(false);
  1698. } else {
  1699. showToast('Error', data.error || 'Failed to save peer', 'error');
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function toggleWGPeerState(iface, pubkey, enable) {
  1706. try {
  1707. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1708. method: 'POST',
  1709. headers: { 'Content-Type': 'application/json' },
  1710. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1711. });
  1712. const data = await res.json();
  1713. if (res.ok) {
  1714. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1715. loadWireGuard(false);
  1716. } else {
  1717. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1718. }
  1719. } catch (err) {
  1720. showToast('Error', err.message, 'error');
  1721. }
  1722. }
  1723. async function deleteWGPeer(iface, pubkey) {
  1724. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1725. try {
  1726. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1727. method: 'POST',
  1728. headers: { 'Content-Type': 'application/json' },
  1729. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1730. });
  1731. const data = await res.json();
  1732. if (res.ok) {
  1733. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1734. loadWireGuard(false);
  1735. } else {
  1736. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1737. }
  1738. } catch (err) {
  1739. showToast('Error', err.message, 'error');
  1740. }
  1741. }
  1742. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1743. function switchIpsecModalTab(tab) {
  1744. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1745. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1746. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1747. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1748. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1749. if (tab === 'p1') {
  1750. if (p1Tab) {
  1751. 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';
  1752. }
  1753. if (p2Tab) {
  1754. 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';
  1755. }
  1756. if (p1Content) p1Content.classList.remove('hidden');
  1757. if (p2Content) p2Content.classList.add('hidden');
  1758. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1759. } else {
  1760. if (p1Tab) {
  1761. 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';
  1762. }
  1763. if (p2Tab) {
  1764. 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';
  1765. }
  1766. if (p1Content) p1Content.classList.add('hidden');
  1767. if (p2Content) p2Content.classList.remove('hidden');
  1768. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1769. }
  1770. }
  1771. function toggleIpsecPhaseStep() {
  1772. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1773. if (p1Content && !p1Content.classList.contains('hidden')) {
  1774. switchIpsecModalTab('p2');
  1775. } else {
  1776. switchIpsecModalTab('p1');
  1777. }
  1778. }
  1779. function toggleIpsecPskVisibility() {
  1780. const pskInput = document.getElementById('ipsec-modal-psk');
  1781. if (!pskInput) return;
  1782. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1783. }
  1784. function addIpsecLocalSubnet(val = '') {
  1785. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1786. if (!container) return;
  1787. const row = document.createElement('div');
  1788. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1789. row.innerHTML = `
  1790. <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">
  1791. <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>
  1792. `;
  1793. container.appendChild(row);
  1794. }
  1795. function addIpsecRemoteSubnet(val = '') {
  1796. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1797. if (!container) return;
  1798. const row = document.createElement('div');
  1799. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1800. row.innerHTML = `
  1801. <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">
  1802. <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>
  1803. `;
  1804. container.appendChild(row);
  1805. }
  1806. function updateIpsecEspProposalFromPFS(val) {
  1807. const prop = document.getElementById('ipsec-modal-espprop');
  1808. if (!prop) return;
  1809. if (val === 'none') {
  1810. prop.value = 'aes256-sha256,aes128-sha256,default';
  1811. } else {
  1812. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1813. }
  1814. }
  1815. function updateIpsecIkeProposalFromDH(dh) {
  1816. const el = document.getElementById('ipsec-modal-ikeprop');
  1817. if (el) {
  1818. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1819. }
  1820. }
  1821. function safeSetVal(id, val) {
  1822. const el = document.getElementById(id);
  1823. if (el) el.value = val;
  1824. }
  1825. function safeSetChecked(id, val) {
  1826. const el = document.getElementById(id);
  1827. if (el) el.checked = !!val;
  1828. }
  1829. function safeGetVal(id, def = '') {
  1830. const el = document.getElementById(id);
  1831. return el ? el.value : def;
  1832. }
  1833. async function loadIPSec(populateInputs = true) {
  1834. try {
  1835. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1836. const list = await res.json();
  1837. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1838. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1839. const badge = document.getElementById('ipsec-sas-badge');
  1840. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1841. const tbody = document.getElementById('ipsec-table-body');
  1842. const empty = document.getElementById('ipsec-empty');
  1843. if (!tbody) return;
  1844. tbody.innerHTML = '';
  1845. if (state.ipsecTunnels.length === 0) {
  1846. if (empty) empty.classList.remove('hidden');
  1847. } else {
  1848. if (empty) empty.classList.add('hidden');
  1849. state.ipsecTunnels.forEach(c => {
  1850. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1851. const tr = document.createElement('tr');
  1852. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1853. // Local subnets tags
  1854. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1855. 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('');
  1856. // Remote subnets tags
  1857. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1858. 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('');
  1859. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1860. const p2Name = c.phase2_name || `${c.name}_p2`;
  1861. tr.innerHTML = `
  1862. <td class="py-2.5 px-3 text-center">
  1863. ${isEstablished ? `
  1864. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1865. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1866. <span>UP</span>
  1867. </span>
  1868. ` : (c.disabled ? `
  1869. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1870. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1871. <span>DOWN</span>
  1872. </span>
  1873. ` : `
  1874. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1875. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1876. <span>IDLE</span>
  1877. </span>
  1878. `)}
  1879. </td>
  1880. <td class="py-2.5 px-4 font-bold text-white">
  1881. <div class="flex items-center gap-2">
  1882. <span class="text-amber-400">🛡</span>
  1883. <div>
  1884. <div>${escapeHtml(c.name)}</div>
  1885. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1886. </div>
  1887. </div>
  1888. </td>
  1889. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1890. <td class="py-2.5 px-4 font-sans">
  1891. <div class="flex items-center gap-1.5">
  1892. <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>
  1893. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1894. </div>
  1895. </td>
  1896. <td class="py-2.5 px-4">
  1897. <div class="space-y-1">
  1898. <div class="flex items-center flex-wrap gap-1">
  1899. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1900. ${localBadges}
  1901. </div>
  1902. <div class="flex items-center flex-wrap gap-1">
  1903. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1904. ${remoteBadges}
  1905. </div>
  1906. </div>
  1907. </td>
  1908. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1909. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1910. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1911. </div>
  1912. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1913. </td>
  1914. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1915. ${isEstablished ? `
  1916. <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>
  1917. ` : `
  1918. <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>
  1919. `}
  1920. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1921. ${c.disabled ? 'Enable' : 'Disable'}
  1922. </button>
  1923. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1924. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1925. </td>
  1926. `;
  1927. tbody.appendChild(tr);
  1928. });
  1929. }
  1930. } catch (err) {
  1931. console.error('Failed to load IPSec:', err);
  1932. }
  1933. }
  1934. function openAddIPSecModal() {
  1935. const modal = document.getElementById('ipsec-modal');
  1936. if (!modal) return;
  1937. const title = document.getElementById('ipsec-modal-title');
  1938. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1939. // Phase 1 Fields
  1940. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1941. const nameEl = document.getElementById('ipsec-modal-name');
  1942. if (nameEl) nameEl.readOnly = false;
  1943. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1944. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1945. safeSetVal('ipsec-modal-remotegw', '');
  1946. safeSetVal('ipsec-modal-localaddrs', '');
  1947. safeSetVal('ipsec-modal-comments', '');
  1948. safeSetVal('ipsec-modal-psk', '');
  1949. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1950. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1951. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1952. safeSetVal('ipsec-modal-localid', '');
  1953. safeSetVal('ipsec-modal-remoteid', '');
  1954. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1955. // Phase 2 Fields
  1956. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1957. safeSetVal('ipsec-modal-espkeylife', '28800');
  1958. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1959. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1960. safeSetChecked('ipsec-modal-autostart', true);
  1961. safeSetChecked('ipsec-modal-disabled', false);
  1962. // Clear & Populate default dynamic subnets
  1963. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1964. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1965. if (localContainer) {
  1966. localContainer.innerHTML = '';
  1967. addIpsecLocalSubnet('192.168.10.0/24');
  1968. }
  1969. if (remoteContainer) {
  1970. remoteContainer.innerHTML = '';
  1971. addIpsecRemoteSubnet('192.168.20.0/24');
  1972. }
  1973. switchIpsecModalTab('p1');
  1974. modal.classList.remove('hidden');
  1975. }
  1976. function openEditIPSecModal(name) {
  1977. const modal = document.getElementById('ipsec-modal');
  1978. if (!modal) return;
  1979. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1980. if (!conn) return;
  1981. const title = document.getElementById('ipsec-modal-title');
  1982. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1983. // Phase 1 Fields
  1984. safeSetVal('ipsec-modal-name', conn.name);
  1985. const nameEl = document.getElementById('ipsec-modal-name');
  1986. if (nameEl) nameEl.readOnly = true;
  1987. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1988. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1989. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1990. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1991. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1992. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1993. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1994. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1995. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1996. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1997. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1998. // Phase 2 Fields
  1999. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2000. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2001. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2002. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2003. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2004. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2005. // Populate dynamic subnets
  2006. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2007. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2008. if (localContainer) {
  2009. localContainer.innerHTML = '';
  2010. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2011. locals.forEach(s => addIpsecLocalSubnet(s));
  2012. }
  2013. if (remoteContainer) {
  2014. remoteContainer.innerHTML = '';
  2015. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2016. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2017. }
  2018. switchIpsecModalTab('p1');
  2019. modal.classList.remove('hidden');
  2020. }
  2021. function closeAddIPSecModal() {
  2022. const modal = document.getElementById('ipsec-modal');
  2023. if (modal) modal.classList.add('hidden');
  2024. }
  2025. async function submitSaveIPSec(e) {
  2026. if (e) e.preventDefault();
  2027. const name = safeGetVal('ipsec-modal-name').trim();
  2028. if (!name) {
  2029. showToast('Error', 'Tunnel name is required', 'error');
  2030. return;
  2031. }
  2032. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2033. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2034. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2035. const comments = safeGetVal('ipsec-modal-comments').trim();
  2036. const psk = safeGetVal('ipsec-modal-psk');
  2037. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2038. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2039. const localId = safeGetVal('ipsec-modal-localid').trim();
  2040. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2041. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2042. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2043. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2044. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2045. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2046. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2047. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2048. // Scrape dynamic local and remote subnets
  2049. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2050. const localSubnets = [];
  2051. localInputs.forEach(inp => {
  2052. const v = inp.value.trim();
  2053. if (v) localSubnets.push(v);
  2054. });
  2055. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2056. const remoteSubnets = [];
  2057. remoteInputs.forEach(inp => {
  2058. const v = inp.value.trim();
  2059. if (v) remoteSubnets.push(v);
  2060. });
  2061. try {
  2062. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2063. method: 'POST',
  2064. headers: { 'Content-Type': 'application/json' },
  2065. body: JSON.stringify({
  2066. name,
  2067. comment: comments,
  2068. ike_version: ikeVersion,
  2069. local_addrs: localAddrs,
  2070. remote_addrs: remotegw,
  2071. preshared_key: psk,
  2072. ike_proposals: ikeProposals,
  2073. ike_keylife: ikeKeylife,
  2074. local_id: localId,
  2075. remote_id: remoteId,
  2076. dpd: dpd,
  2077. phase2_name: phase2Name,
  2078. esp_proposals: espProposals,
  2079. esp_keylife: espKeylife,
  2080. pfs_group: pfsGroup,
  2081. pfs: pfsGroup !== 'none',
  2082. local_subnets: localSubnets,
  2083. remote_subnets: remoteSubnets,
  2084. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2085. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2086. auto_start: autostart,
  2087. disabled
  2088. })
  2089. });
  2090. if (res.ok) {
  2091. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2092. closeAddIPSecModal();
  2093. loadIPSec(false);
  2094. } else {
  2095. const err = await res.json();
  2096. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2097. }
  2098. } catch (err) {
  2099. showToast('Error', err.message, 'error');
  2100. }
  2101. }
  2102. async function startIPSecTunnel(name) {
  2103. try {
  2104. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2105. if (res.ok) {
  2106. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2107. setTimeout(() => loadIPSec(false), 2000);
  2108. }
  2109. } catch (err) {
  2110. showToast('Error', err.message, 'error');
  2111. }
  2112. }
  2113. async function stopIPSecTunnel(name) {
  2114. try {
  2115. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2116. if (res.ok) {
  2117. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2118. loadIPSec(false);
  2119. }
  2120. } catch (err) {
  2121. showToast('Error', err.message, 'error');
  2122. }
  2123. }
  2124. async function toggleIPSecState(name, enable) {
  2125. try {
  2126. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2127. method: 'POST',
  2128. headers: { 'Content-Type': 'application/json' },
  2129. body: JSON.stringify({ enabled: enable })
  2130. });
  2131. if (res.ok) {
  2132. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2133. loadIPSec(false);
  2134. }
  2135. } catch (err) {
  2136. showToast('Error', err.message, 'error');
  2137. }
  2138. }
  2139. async function deleteIPSecConn(name) {
  2140. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2141. try {
  2142. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2143. if (res.ok) {
  2144. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2145. loadIPSec(false);
  2146. fetchData(false);
  2147. }
  2148. } catch (err) {
  2149. showToast('Error', err.message, 'error');
  2150. }
  2151. }
  2152. // ======================== L2TP Multi-Instance ========================
  2153. async function loadL2TP(populateInputs = true) {
  2154. try {
  2155. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2156. await fetchPPPProfilesList();
  2157. }
  2158. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2159. const list = await res.json();
  2160. state.l2tpList = Array.isArray(list) ? list : [];
  2161. const badge = document.getElementById('l2tp-count-badge');
  2162. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2163. const tbody = document.getElementById('l2tp-table-body');
  2164. const empty = document.getElementById('l2tp-empty');
  2165. if (!tbody) return;
  2166. tbody.innerHTML = '';
  2167. if (state.l2tpList.length === 0) {
  2168. if (empty) empty.classList.remove('hidden');
  2169. } else {
  2170. if (empty) empty.classList.add('hidden');
  2171. state.l2tpList.forEach(inst => {
  2172. const tr = document.createElement('tr');
  2173. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2174. tr.innerHTML = `
  2175. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2176. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2177. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2178. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2179. <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>
  2180. <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>
  2181. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2182. <td class="py-2.5 px-3 text-center">
  2183. <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'}">
  2184. ${inst.default_route ? 'Yes' : 'No'}
  2185. </span>
  2186. </td>
  2187. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2188. ${inst.running ? `
  2189. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2190. ` : `
  2191. <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>
  2192. `}
  2193. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2194. ${inst.disabled ? 'Enable' : 'Disable'}
  2195. </button>
  2196. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2197. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2198. </td>
  2199. `;
  2200. tbody.appendChild(tr);
  2201. });
  2202. }
  2203. } catch (err) {
  2204. console.error('Failed to load L2TP:', err);
  2205. }
  2206. }
  2207. async function openAddL2TPModal() {
  2208. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2209. await fetchPPPProfilesList();
  2210. }
  2211. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2212. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2213. document.getElementById('l2tp-modal-name').readOnly = false;
  2214. document.getElementById('l2tp-modal-server').value = '';
  2215. document.getElementById('l2tp-modal-user').value = '';
  2216. document.getElementById('l2tp-modal-pass').value = '';
  2217. document.getElementById('l2tp-modal-ipsec').value = '';
  2218. document.getElementById('l2tp-modal-defroute').checked = true;
  2219. document.getElementById('l2tp-modal-disabled').checked = false;
  2220. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2221. document.getElementById('l2tp-modal').classList.remove('hidden');
  2222. }
  2223. async function openEditL2TPModal(name) {
  2224. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2225. await fetchPPPProfilesList();
  2226. }
  2227. const inst = (state.l2tpList || []).find(i => i.name === name);
  2228. if (!inst) return;
  2229. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2230. document.getElementById('l2tp-modal-name').value = inst.name;
  2231. document.getElementById('l2tp-modal-name').readOnly = true;
  2232. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2233. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2234. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2235. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2236. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2237. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2238. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2239. document.getElementById('l2tp-modal').classList.remove('hidden');
  2240. }
  2241. function closeL2TPModal() {
  2242. document.getElementById('l2tp-modal').classList.add('hidden');
  2243. }
  2244. async function submitSaveL2TP(e) {
  2245. e.preventDefault();
  2246. const name = document.getElementById('l2tp-modal-name').value.trim();
  2247. const server = document.getElementById('l2tp-modal-server').value.trim();
  2248. const user = document.getElementById('l2tp-modal-user').value.trim();
  2249. const pass = document.getElementById('l2tp-modal-pass').value;
  2250. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2251. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2252. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2253. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2254. try {
  2255. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2256. method: 'POST',
  2257. headers: { 'Content-Type': 'application/json' },
  2258. body: JSON.stringify({
  2259. name,
  2260. connect_to: server,
  2261. username: user,
  2262. password: pass,
  2263. profile: profile,
  2264. ipsec_secret: ipsec,
  2265. default_route: defRoute,
  2266. disabled
  2267. })
  2268. });
  2269. if (res.ok) {
  2270. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2271. closeL2TPModal();
  2272. loadL2TP(false);
  2273. fetchData(false);
  2274. }
  2275. } catch (err) {
  2276. showToast('Error', err.message, 'error');
  2277. }
  2278. }
  2279. async function connectL2TPInstance(name) {
  2280. try {
  2281. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2282. if (res.ok) {
  2283. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2284. setTimeout(() => loadL2TP(false), 2000);
  2285. }
  2286. } catch (err) {
  2287. showToast('Error', err.message, 'error');
  2288. }
  2289. }
  2290. async function disconnectL2TPInstance(name) {
  2291. try {
  2292. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2293. if (res.ok) {
  2294. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2295. loadL2TP(false);
  2296. }
  2297. } catch (err) {
  2298. showToast('Error', err.message, 'error');
  2299. }
  2300. }
  2301. async function toggleL2TPState(name, enable) {
  2302. try {
  2303. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2304. method: 'POST',
  2305. headers: { 'Content-Type': 'application/json' },
  2306. body: JSON.stringify({ enabled: enable })
  2307. });
  2308. if (res.ok) {
  2309. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2310. loadL2TP(false);
  2311. }
  2312. } catch (err) {
  2313. showToast('Error', err.message, 'error');
  2314. }
  2315. }
  2316. async function deleteL2TPInstance(name) {
  2317. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2318. try {
  2319. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2320. if (res.ok) {
  2321. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2322. loadL2TP(false);
  2323. fetchData(false);
  2324. }
  2325. } catch (err) {
  2326. showToast('Error', err.message, 'error');
  2327. }
  2328. }
  2329. // ======================== PPTP Multi-Instance ========================
  2330. async function loadPPTP(populateInputs = true) {
  2331. try {
  2332. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2333. await fetchPPPProfilesList();
  2334. }
  2335. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2336. const list = await res.json();
  2337. state.pptpList = Array.isArray(list) ? list : [];
  2338. const badge = document.getElementById('pptp-count-badge');
  2339. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2340. const tbody = document.getElementById('pptp-table-body');
  2341. const empty = document.getElementById('pptp-empty');
  2342. if (!tbody) return;
  2343. tbody.innerHTML = '';
  2344. if (state.pptpList.length === 0) {
  2345. if (empty) empty.classList.remove('hidden');
  2346. } else {
  2347. if (empty) empty.classList.add('hidden');
  2348. state.pptpList.forEach(inst => {
  2349. const tr = document.createElement('tr');
  2350. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2351. tr.innerHTML = `
  2352. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2353. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2354. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2355. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2356. <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>
  2357. <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>
  2358. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2359. <td class="py-2.5 px-3 text-center">
  2360. <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'}">
  2361. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2362. </span>
  2363. </td>
  2364. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2365. ${inst.running ? `
  2366. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2367. ` : `
  2368. <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>
  2369. `}
  2370. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2371. ${inst.disabled ? 'Enable' : 'Disable'}
  2372. </button>
  2373. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2374. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2375. </td>
  2376. `;
  2377. tbody.appendChild(tr);
  2378. });
  2379. }
  2380. } catch (err) {
  2381. console.error('Failed to load PPTP:', err);
  2382. }
  2383. }
  2384. async function openAddPPTPModal() {
  2385. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2386. await fetchPPPProfilesList();
  2387. }
  2388. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2389. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2390. document.getElementById('pptp-modal-name').readOnly = false;
  2391. document.getElementById('pptp-modal-server').value = '';
  2392. document.getElementById('pptp-modal-user').value = '';
  2393. document.getElementById('pptp-modal-pass').value = '';
  2394. document.getElementById('pptp-modal-mppe').checked = true;
  2395. document.getElementById('pptp-modal-defroute').checked = true;
  2396. document.getElementById('pptp-modal-disabled').checked = false;
  2397. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2398. document.getElementById('pptp-modal').classList.remove('hidden');
  2399. }
  2400. async function openEditPPTPModal(name) {
  2401. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2402. await fetchPPPProfilesList();
  2403. }
  2404. const inst = (state.pptpList || []).find(i => i.name === name);
  2405. if (!inst) return;
  2406. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2407. document.getElementById('pptp-modal-name').value = inst.name;
  2408. document.getElementById('pptp-modal-name').readOnly = true;
  2409. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2410. document.getElementById('pptp-modal-user').value = inst.username || '';
  2411. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2412. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2413. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2414. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2415. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2416. document.getElementById('pptp-modal').classList.remove('hidden');
  2417. }
  2418. function closePPTPModal() {
  2419. document.getElementById('pptp-modal').classList.add('hidden');
  2420. }
  2421. async function submitSavePPTP(e) {
  2422. e.preventDefault();
  2423. const name = document.getElementById('pptp-modal-name').value.trim();
  2424. const server = document.getElementById('pptp-modal-server').value.trim();
  2425. const user = document.getElementById('pptp-modal-user').value.trim();
  2426. const pass = document.getElementById('pptp-modal-pass').value;
  2427. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2428. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2429. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2430. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2431. try {
  2432. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2433. method: 'POST',
  2434. headers: { 'Content-Type': 'application/json' },
  2435. body: JSON.stringify({
  2436. name,
  2437. connect_to: server,
  2438. username: user,
  2439. password: pass,
  2440. profile: profile,
  2441. require_mppe: mppe,
  2442. default_route: defRoute,
  2443. auto_reconnect: true,
  2444. disabled
  2445. })
  2446. });
  2447. if (res.ok) {
  2448. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2449. closePPTPModal();
  2450. loadPPTP(false);
  2451. fetchData(false);
  2452. }
  2453. } catch (err) {
  2454. showToast('Error', err.message, 'error');
  2455. }
  2456. }
  2457. async function connectPPTPInstance(name) {
  2458. try {
  2459. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2460. if (res.ok) {
  2461. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2462. setTimeout(() => loadPPTP(false), 2000);
  2463. }
  2464. } catch (err) {
  2465. showToast('Error', err.message, 'error');
  2466. }
  2467. }
  2468. async function disconnectPPTPInstance(name) {
  2469. try {
  2470. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2471. if (res.ok) {
  2472. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2473. loadPPTP(false);
  2474. }
  2475. } catch (err) {
  2476. showToast('Error', err.message, 'error');
  2477. }
  2478. }
  2479. async function togglePPTPState(name, enable) {
  2480. try {
  2481. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2482. method: 'POST',
  2483. headers: { 'Content-Type': 'application/json' },
  2484. body: JSON.stringify({ enabled: enable })
  2485. });
  2486. if (res.ok) {
  2487. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2488. loadPPTP(false);
  2489. }
  2490. } catch (err) {
  2491. showToast('Error', err.message, 'error');
  2492. }
  2493. }
  2494. async function deletePPTPInstance(name) {
  2495. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2496. try {
  2497. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2498. if (res.ok) {
  2499. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2500. loadPPTP(false);
  2501. fetchData(false);
  2502. }
  2503. } catch (err) {
  2504. showToast('Error', err.message, 'error');
  2505. }
  2506. }
  2507. // ---------------- Modal & Helper Functions ----------------
  2508. function openVlanModal(defaultParent = '') {
  2509. const select = document.getElementById('vlan-parent');
  2510. select.innerHTML = '';
  2511. const allIfaces = state.interfaces || [];
  2512. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2513. if (eligible.length === 0) {
  2514. const opt = document.createElement('option');
  2515. opt.value = '';
  2516. opt.innerText = 'No VLAN-capable interfaces available';
  2517. select.appendChild(opt);
  2518. } else {
  2519. eligible.forEach(i => {
  2520. const opt = document.createElement('option');
  2521. opt.value = i.name;
  2522. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2523. if (i.name === defaultParent) opt.selected = true;
  2524. select.appendChild(opt);
  2525. });
  2526. }
  2527. document.getElementById('vlan-id').value = '';
  2528. document.getElementById('vlan-name').value = '';
  2529. document.getElementById('vlan-ip').value = '';
  2530. document.getElementById('vlan-desc').value = '';
  2531. autoSuggestVlanName();
  2532. document.getElementById('vlan-modal').classList.remove('hidden');
  2533. }
  2534. function closeVlanModal() {
  2535. document.getElementById('vlan-modal').classList.add('hidden');
  2536. }
  2537. function autoSuggestVlanName() {
  2538. const parent = document.getElementById('vlan-parent').value;
  2539. if (!parent) return;
  2540. const id = document.getElementById('vlan-id').value;
  2541. const nameInput = document.getElementById('vlan-name');
  2542. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2543. }
  2544. function setSubnetPreset(cidr) {
  2545. const ipInput = document.getElementById('vlan-ip');
  2546. const id = document.getElementById('vlan-id').value || '10';
  2547. ipInput.value = `192.168.${id}.1${cidr}`;
  2548. }
  2549. async function submitCreateVlan(e) {
  2550. e.preventDefault();
  2551. const btn = document.getElementById('vlan-submit-btn');
  2552. btn.disabled = true;
  2553. btn.innerText = 'Creating...';
  2554. const parent = document.getElementById('vlan-parent').value;
  2555. if (!parent) {
  2556. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2557. btn.disabled = false;
  2558. btn.innerText = 'Create VLAN';
  2559. return;
  2560. }
  2561. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2562. const name = document.getElementById('vlan-name').value.trim();
  2563. const ip = document.getElementById('vlan-ip').value.trim();
  2564. const role = document.getElementById('vlan-role').value;
  2565. const desc = document.getElementById('vlan-desc').value.trim();
  2566. try {
  2567. const res = await fetch(`${API_BASE}/vlans`, {
  2568. method: 'POST',
  2569. headers: { 'Content-Type': 'application/json' },
  2570. body: JSON.stringify({
  2571. parent_name: parent,
  2572. vlan_id: id,
  2573. name: name,
  2574. ip_address: ip,
  2575. role: role,
  2576. description: desc,
  2577. mtu: 1500,
  2578. auto_up: true
  2579. })
  2580. });
  2581. const data = await res.json();
  2582. if (res.ok) {
  2583. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2584. state.expandedParents.add(parent);
  2585. closeVlanModal();
  2586. await fetchData(true);
  2587. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2588. } else {
  2589. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2590. }
  2591. } catch (err) {
  2592. showToast('Error', err.message, 'error');
  2593. } finally {
  2594. btn.disabled = false;
  2595. btn.innerText = 'Create VLAN';
  2596. }
  2597. }
  2598. async function confirmDeleteVlan(name) {
  2599. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2600. try {
  2601. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2602. if (res.ok) {
  2603. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2604. closeIfaceModal();
  2605. fetchData(true);
  2606. }
  2607. } catch (err) {
  2608. showToast('Error', err.message, 'error');
  2609. }
  2610. }
  2611. function openIfaceModal(name) {
  2612. const iface = (state.interfaces || []).find(i => i.name === name);
  2613. if (!iface) return;
  2614. state.currentModalIface = iface.name;
  2615. document.getElementById('modal-iface-name').innerText = iface.name;
  2616. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2617. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2618. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2619. document.getElementById('modal-iface-desc').value = iface.description || '';
  2620. const nameInput = document.getElementById('modal-iface-new-name');
  2621. const renameBtn = document.getElementById('modal-btn-rename');
  2622. const renameHelp = document.getElementById('modal-iface-rename-help');
  2623. if (nameInput) {
  2624. nameInput.value = iface.name;
  2625. if (iface.name === 'lo' || iface.type === 'loopback') {
  2626. nameInput.disabled = true;
  2627. if (renameBtn) renameBtn.disabled = true;
  2628. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  2629. } else {
  2630. nameInput.disabled = false;
  2631. if (renameBtn) renameBtn.disabled = false;
  2632. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  2633. }
  2634. }
  2635. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2636. if (iface.is_vlan) {
  2637. delBtn.classList.remove('hidden');
  2638. } else {
  2639. delBtn.classList.add('hidden');
  2640. }
  2641. renderModalIPs(iface);
  2642. document.getElementById('iface-modal').classList.remove('hidden');
  2643. }
  2644. function renderModalIPs(iface) {
  2645. const container = document.getElementById('modal-ip-list');
  2646. container.innerHTML = '';
  2647. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2648. if (addrs.length === 0) {
  2649. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2650. return;
  2651. }
  2652. addrs.forEach(addr => {
  2653. const row = document.createElement('div');
  2654. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2655. row.innerHTML = `
  2656. <span class="text-white">${addr}</span>
  2657. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2658. `;
  2659. container.appendChild(row);
  2660. });
  2661. }
  2662. function closeIfaceModal() {
  2663. document.getElementById('iface-modal').classList.add('hidden');
  2664. state.currentModalIface = null;
  2665. }
  2666. async function setIfaceState(name, newState) {
  2667. const target = name || state.currentModalIface;
  2668. if (!target) return;
  2669. await toggleInterfaceState(target, newState);
  2670. const updated = (state.interfaces || []).find(i => i.name === target);
  2671. if (updated) openIfaceModal(target);
  2672. }
  2673. async function applyMTU() {
  2674. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2675. try {
  2676. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2677. method: 'POST',
  2678. headers: { 'Content-Type': 'application/json' },
  2679. body: JSON.stringify({ mtu })
  2680. });
  2681. if (res.ok) {
  2682. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2683. fetchData(false);
  2684. }
  2685. } catch (err) {
  2686. showToast('Error', err.message, 'error');
  2687. }
  2688. }
  2689. async function addInterfaceIP() {
  2690. const ip = document.getElementById('modal-new-ip').value.trim();
  2691. if (!ip) return;
  2692. try {
  2693. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2694. method: 'POST',
  2695. headers: { 'Content-Type': 'application/json' },
  2696. body: JSON.stringify({ ip })
  2697. });
  2698. if (res.ok) {
  2699. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2700. document.getElementById('modal-new-ip').value = '';
  2701. await fetchData(false);
  2702. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2703. if (iface) renderModalIPs(iface);
  2704. } else {
  2705. const err = await res.json();
  2706. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2707. }
  2708. } catch (err) {
  2709. showToast('Error', err.message, 'error');
  2710. }
  2711. }
  2712. async function removeInterfaceIP(ip) {
  2713. if (!confirm(`Remove IP ${ip}?`)) return;
  2714. try {
  2715. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2716. method: 'DELETE',
  2717. headers: { 'Content-Type': 'application/json' },
  2718. body: JSON.stringify({ ip })
  2719. });
  2720. if (res.ok) {
  2721. showToast('IP Removed', `Removed ${ip}`, 'success');
  2722. await fetchData(false);
  2723. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2724. if (iface) renderModalIPs(iface);
  2725. }
  2726. } catch (err) {
  2727. showToast('Error', err.message, 'error');
  2728. }
  2729. }
  2730. async function renameInterface() {
  2731. const oldName = state.currentModalIface;
  2732. const newNameInput = document.getElementById('modal-iface-new-name');
  2733. const newName = (newNameInput?.value || '').trim();
  2734. if (!oldName) return;
  2735. if (!newName) {
  2736. showToast('Warning', 'Interface name cannot be empty', 'warning');
  2737. return;
  2738. }
  2739. if (newName === oldName) {
  2740. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  2741. return;
  2742. }
  2743. if (newName.length > 15) {
  2744. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  2745. return;
  2746. }
  2747. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  2748. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  2749. return;
  2750. }
  2751. const renameBtn = document.getElementById('modal-btn-rename');
  2752. if (renameBtn) {
  2753. renameBtn.disabled = true;
  2754. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  2755. }
  2756. try {
  2757. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2758. method: 'POST',
  2759. headers: { 'Content-Type': 'application/json' },
  2760. body: JSON.stringify({ new_name: newName })
  2761. });
  2762. const data = await res.json();
  2763. if (!res.ok) {
  2764. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  2765. return;
  2766. }
  2767. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  2768. state.currentModalIface = newName;
  2769. document.getElementById('modal-iface-name').innerText = newName;
  2770. // Refresh application state
  2771. await fetchData(false);
  2772. const updated = (state.interfaces || []).find(i => i.name === newName);
  2773. if (updated) {
  2774. openIfaceModal(newName);
  2775. } else {
  2776. closeIfaceModal();
  2777. }
  2778. } catch (err) {
  2779. showToast('Error', err.message, 'error');
  2780. } finally {
  2781. if (renameBtn) {
  2782. renameBtn.disabled = false;
  2783. renameBtn.innerHTML = `
  2784. <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>
  2785. <span>Rename</span>
  2786. `;
  2787. }
  2788. }
  2789. }
  2790. async function saveInterfaceMetadata() {
  2791. const oldName = state.currentModalIface;
  2792. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  2793. const role = document.getElementById('modal-iface-role').value;
  2794. const desc = document.getElementById('modal-iface-desc').value.trim();
  2795. let targetName = oldName;
  2796. // If user changed the name before clicking Save Changes, execute rename first
  2797. if (newName && newName !== oldName && oldName !== 'lo') {
  2798. try {
  2799. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2800. method: 'POST',
  2801. headers: { 'Content-Type': 'application/json' },
  2802. body: JSON.stringify({ new_name: newName })
  2803. });
  2804. const data = await renameRes.json();
  2805. if (!renameRes.ok) {
  2806. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  2807. return;
  2808. }
  2809. targetName = newName;
  2810. state.currentModalIface = newName;
  2811. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  2812. } catch (err) {
  2813. showToast('Error', err.message, 'error');
  2814. return;
  2815. }
  2816. }
  2817. try {
  2818. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  2819. method: 'POST',
  2820. headers: { 'Content-Type': 'application/json' },
  2821. body: JSON.stringify({ role, description: desc })
  2822. });
  2823. if (res.ok) {
  2824. showToast('Saved', 'Interface configuration updated', 'success');
  2825. closeIfaceModal();
  2826. fetchData(false);
  2827. } else {
  2828. const err = await res.json();
  2829. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  2830. }
  2831. } catch (err) {
  2832. showToast('Error', err.message, 'error');
  2833. }
  2834. }
  2835. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2836. state.fwSubTab = 'filter';
  2837. state.routesSubTab = 'routes';
  2838. function renderRuleFlag(disabled, hasComment) {
  2839. let flags = '';
  2840. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2841. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2842. return flags || '<span class="text-slate-600">-</span>';
  2843. }
  2844. function renderActionBadge(action) {
  2845. const act = (action || '').toLowerCase();
  2846. let color = 'bg-slate-800 text-slate-300';
  2847. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2848. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2849. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2850. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2851. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2852. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2853. }
  2854. function switchFWSubTab(tab) {
  2855. state.fwSubTab = tab;
  2856. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2857. tabs.forEach(t => {
  2858. const panel = document.getElementById(`fw-subtab-${t}`);
  2859. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2860. if (panel) {
  2861. if (t === tab) panel.classList.remove('hidden');
  2862. else panel.classList.add('hidden');
  2863. }
  2864. if (btn) {
  2865. if (t === tab) {
  2866. 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';
  2867. } else {
  2868. 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';
  2869. }
  2870. }
  2871. });
  2872. const addBtn = document.getElementById('fw-primary-add-btn');
  2873. if (addBtn) {
  2874. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2875. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2876. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2877. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2878. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2879. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2880. }
  2881. if (tab === 'geo') loadGeoIP();
  2882. if (tab === 'connections') loadConnections();
  2883. setTimeout(initTableSorting, 50);
  2884. }
  2885. function openCurrentFWModal() {
  2886. if (state.fwSubTab === 'filter') openAddFilterModal();
  2887. else if (state.fwSubTab === 'nat') openAddNATModal();
  2888. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2889. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2890. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2891. else if (state.fwSubTab === 'connections') loadConnections();
  2892. }
  2893. async function loadFirewall(populateDropdowns = true) {
  2894. try {
  2895. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2896. fetch(`${API_BASE}/firewall/summary`),
  2897. fetch(`${API_BASE}/firewall/filter`),
  2898. fetch(`${API_BASE}/firewall/nat`),
  2899. fetch(`${API_BASE}/firewall/mangle`),
  2900. fetch(`${API_BASE}/firewall/address-lists`),
  2901. fetch(`${API_BASE}/firewall/geoip/status`),
  2902. fetch(`${API_BASE}/firewall/geoip/countries`)
  2903. ]);
  2904. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2905. if (filterRes.ok) state.filterRules = await filterRes.json();
  2906. if (natRes.ok) state.natRules = await natRes.json();
  2907. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2908. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2909. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2910. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2911. // Badges
  2912. const bFilter = document.getElementById('fw-badge-filter');
  2913. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2914. const bNat = document.getElementById('fw-badge-nat');
  2915. if (bNat) bNat.innerText = (state.natRules || []).length;
  2916. const bMangle = document.getElementById('fw-badge-mangle');
  2917. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2918. const bAddr = document.getElementById('fw-badge-addrlist');
  2919. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2920. const bGeo = document.getElementById('fw-badge-geo');
  2921. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2922. renderFilterRules();
  2923. renderNATRules();
  2924. renderMangleRules();
  2925. renderAddressLists();
  2926. renderGeoCountries();
  2927. if (state.fwSubTab === 'connections') {
  2928. loadConnections();
  2929. }
  2930. } catch (err) {
  2931. console.error('Failed to load firewall:', err);
  2932. }
  2933. }
  2934. // ----------------- Filter Rules -----------------
  2935. function renderFilterRules() {
  2936. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2937. const tbody = document.getElementById('filter-table-body');
  2938. const empty = document.getElementById('filter-empty');
  2939. if (!tbody) return;
  2940. tbody.innerHTML = '';
  2941. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2942. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2943. if (rules.length === 0) {
  2944. empty?.classList.remove('hidden');
  2945. return;
  2946. }
  2947. empty?.classList.add('hidden');
  2948. rules.forEach((r, idx) => {
  2949. const tr = document.createElement('tr');
  2950. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2951. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2952. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2953. let actionExtra = '';
  2954. if (r.action === 'reject') {
  2955. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2956. } else if (r.action === 'jump') {
  2957. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2958. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2959. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2960. } else if (r.action === 'log' && r.log_prefix) {
  2961. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2962. }
  2963. tr.innerHTML = `
  2964. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2965. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2966. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2967. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2968. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2969. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2970. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2971. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2972. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2973. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2974. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2975. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2976. </td>
  2977. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2978. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2979. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2980. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2981. <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>
  2982. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2983. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2984. </td>
  2985. `;
  2986. tbody.appendChild(tr);
  2987. });
  2988. }
  2989. function formatTarget(addr, list, geo) {
  2990. const parts = [];
  2991. if (addr) parts.push(`<span>${addr}</span>`);
  2992. if (list) {
  2993. const inv = list.startsWith('!') ? '!' : '';
  2994. const clean = list.replace(/^!/, '');
  2995. 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>`);
  2996. }
  2997. if (geo) {
  2998. const inv = geo.startsWith('!') ? '!' : '';
  2999. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3000. 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>`);
  3001. }
  3002. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3003. return parts.join(' ');
  3004. }
  3005. function populateInterfaceSelect(selectId, currentVal = '') {
  3006. const sel = document.getElementById(selectId);
  3007. if (!sel) return;
  3008. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3009. (state.interfaces || []).forEach(i => {
  3010. const opt = document.createElement('option');
  3011. opt.value = i.name;
  3012. opt.innerText = `${i.name} (${i.role || i.type})`;
  3013. if (i.name === currentVal) opt.selected = true;
  3014. sel.appendChild(opt);
  3015. });
  3016. }
  3017. function populateAddressListSelect(selectId, currentVal = '') {
  3018. const sel = document.getElementById(selectId);
  3019. if (!sel) return;
  3020. sel.innerHTML = '<option value="">(None)</option>';
  3021. const cleanVal = (currentVal || '').replace(/^!/, '');
  3022. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3023. customNames.forEach(name => {
  3024. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3025. const opt = document.createElement('option');
  3026. opt.value = name;
  3027. opt.innerText = `${name} (${count} entries)`;
  3028. if (name === cleanVal) opt.selected = true;
  3029. sel.appendChild(opt);
  3030. });
  3031. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3032. const opt = document.createElement('option');
  3033. opt.value = cleanVal;
  3034. opt.innerText = cleanVal;
  3035. opt.selected = true;
  3036. sel.appendChild(opt);
  3037. }
  3038. populateCommonAddrListDatalist();
  3039. }
  3040. function populateCommonAddrListDatalist() {
  3041. const dl = document.getElementById('fw-addrlist-datalist');
  3042. if (!dl) return;
  3043. dl.innerHTML = '';
  3044. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3045. names.forEach(name => {
  3046. const opt = document.createElement('option');
  3047. opt.value = name;
  3048. dl.appendChild(opt);
  3049. });
  3050. }
  3051. function populateGeoIPSelect(selectId, currentVal = '') {
  3052. const sel = document.getElementById(selectId);
  3053. if (!sel) return;
  3054. sel.innerHTML = '<option value="">(None)</option>';
  3055. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3056. // Presets optgroup
  3057. const grpPresets = document.createElement('optgroup');
  3058. grpPresets.label = '⚡ Regional Presets';
  3059. const presets = [
  3060. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3061. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3062. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3063. ];
  3064. presets.forEach(p => {
  3065. const opt = document.createElement('option');
  3066. opt.value = p.code;
  3067. opt.innerText = p.label;
  3068. if (p.code === cleanVal) opt.selected = true;
  3069. grpPresets.appendChild(opt);
  3070. });
  3071. sel.appendChild(grpPresets);
  3072. // All Countries optgroup
  3073. const grpCountries = document.createElement('optgroup');
  3074. grpCountries.label = '🌍 All Countries';
  3075. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3076. countries.forEach(c => {
  3077. const opt = document.createElement('option');
  3078. opt.value = c.code;
  3079. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3080. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3081. if (c.code === cleanVal) opt.selected = true;
  3082. grpCountries.appendChild(opt);
  3083. });
  3084. sel.appendChild(grpCountries);
  3085. }
  3086. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3087. function switchFwRuleTab(tab) {
  3088. state.activeFwRuleTab = tab;
  3089. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3090. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3091. btn.classList.add('text-slate-400', 'border-transparent');
  3092. });
  3093. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3094. if (activeBtn) {
  3095. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3096. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3097. }
  3098. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3099. const activePane = document.getElementById(`fw-pane-${tab}`);
  3100. if (activePane) activePane.classList.remove('hidden');
  3101. if (tab === 'statistics') {
  3102. startFwStatPolling();
  3103. } else {
  3104. stopFwStatPolling();
  3105. }
  3106. }
  3107. function toggleFwField(fieldKey, expand) {
  3108. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3109. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3110. if (!plusBtn || !fieldBox) return;
  3111. if (expand) {
  3112. plusBtn.classList.add('hidden');
  3113. fieldBox.classList.remove('hidden');
  3114. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3115. if (valInput) valInput.focus();
  3116. } else {
  3117. fieldBox.classList.add('hidden');
  3118. plusBtn.classList.remove('hidden');
  3119. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3120. if (valInput) {
  3121. if (valInput.tagName === 'SELECT') {
  3122. valInput.selectedIndex = 0;
  3123. } else {
  3124. valInput.value = '';
  3125. }
  3126. }
  3127. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3128. if (invInput) invInput.checked = false;
  3129. if (fieldKey === 'cs') {
  3130. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3131. const el = document.getElementById(id);
  3132. if (el) el.checked = false;
  3133. });
  3134. }
  3135. if (fieldKey === 'natstate') {
  3136. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3137. const el = document.getElementById(id);
  3138. if (el) el.checked = false;
  3139. });
  3140. }
  3141. if (fieldKey === 'days') {
  3142. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3143. const el = document.getElementById(`fw-day-${d}`);
  3144. if (el) el.checked = true;
  3145. });
  3146. }
  3147. }
  3148. }
  3149. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3150. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3151. toggleFwField(fieldKey, true);
  3152. let strVal = String(value);
  3153. if (hasInvert) {
  3154. const inv = strVal.startsWith('!');
  3155. if (inv) strVal = strVal.slice(1);
  3156. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3157. if (invEl) invEl.checked = inv;
  3158. }
  3159. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3160. if (valEl) valEl.value = strVal;
  3161. } else {
  3162. toggleFwField(fieldKey, false);
  3163. }
  3164. }
  3165. function getFwFieldVal(fieldKey, hasInvert = false) {
  3166. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3167. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3168. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3169. let v = valEl ? valEl.value.trim() : '';
  3170. if (!v) return '';
  3171. if (hasInvert) {
  3172. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3173. if (invEl && invEl.checked) {
  3174. v = '!' + v.replace(/^!/, '');
  3175. }
  3176. }
  3177. return v;
  3178. }
  3179. function toggleMaximizeFilterModal() {
  3180. const win = document.getElementById('filter-modal-window');
  3181. if (!win) return;
  3182. if (win.classList.contains('max-w-[720px]')) {
  3183. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3184. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3185. } else {
  3186. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3187. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3188. }
  3189. }
  3190. function openAddFilterModal() {
  3191. switchFwRuleTab('general');
  3192. const badge = document.getElementById('fw-modal-badge');
  3193. if (badge) badge.innerText = 'New...';
  3194. document.getElementById('filter-modal-id').value = '';
  3195. document.getElementById('filter-modal-enabled').checked = true;
  3196. document.getElementById('filter-modal-comment').value = '';
  3197. document.getElementById('filter-modal-chain').value = 'forward';
  3198. document.getElementById('filter-modal-action').value = 'accept';
  3199. document.getElementById('filter-modal-log').checked = false;
  3200. populateInterfaceSelect('fw-val-iniface');
  3201. populateInterfaceSelect('fw-val-outiface');
  3202. populateAddressListSelect('fw-val-srclist');
  3203. populateAddressListSelect('fw-val-dstlist');
  3204. populateGeoIPSelect('fw-val-srcgeo');
  3205. populateGeoIPSelect('fw-val-dstgeo');
  3206. const allFieldKeys = [
  3207. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3208. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3209. 'routingmark', 'conntype', 'cs', 'natstate',
  3210. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3211. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3212. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3213. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3214. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3215. ];
  3216. allFieldKeys.forEach(k => toggleFwField(k, false));
  3217. resetCurrentRuleCounters();
  3218. toggleFilterActionFields();
  3219. document.getElementById('filter-modal').classList.remove('hidden');
  3220. }
  3221. function openEditFilterModal(id) {
  3222. const r = (state.filterRules || []).find(rule => rule.id === id);
  3223. if (!r) return;
  3224. switchFwRuleTab('general');
  3225. const badge = document.getElementById('fw-modal-badge');
  3226. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3227. document.getElementById('filter-modal-id').value = r.id;
  3228. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3229. document.getElementById('filter-modal-comment').value = r.comment || '';
  3230. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3231. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3232. document.getElementById('filter-modal-log').checked = !!r.log;
  3233. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3234. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3235. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3236. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3237. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3238. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3239. setFwFieldVal('src', r.src_address, true);
  3240. setFwFieldVal('dst', r.dst_address, true);
  3241. setFwFieldVal('srclist', r.src_address_list, true);
  3242. setFwFieldVal('dstlist', r.dst_address_list, true);
  3243. setFwFieldVal('srcgeo', r.src_geoip, true);
  3244. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3245. if (r.protocol && r.protocol !== 'all') {
  3246. setFwFieldVal('proto', r.protocol, true);
  3247. } else {
  3248. toggleFwField('proto', false);
  3249. }
  3250. setFwFieldVal('sport', r.src_port, true);
  3251. setFwFieldVal('dport', r.dst_port, true);
  3252. setFwFieldVal('anyport', r.any_port, true);
  3253. setFwFieldVal('iniface', r.in_interface, true);
  3254. setFwFieldVal('outiface', r.out_interface, true);
  3255. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3256. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3257. setFwFieldVal('pktmark', r.packet_mark, true);
  3258. setFwFieldVal('connmark', r.connection_mark, true);
  3259. setFwFieldVal('routingmark', r.routing_mark, true);
  3260. setFwFieldVal('conntype', r.connection_type, false);
  3261. const states = r.connection_state || [];
  3262. if (states.length > 0) {
  3263. toggleFwField('cs', true);
  3264. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3265. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3266. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3267. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3268. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3269. } else {
  3270. toggleFwField('cs', false);
  3271. }
  3272. const natStates = r.connection_nat_state || [];
  3273. if (natStates.length > 0) {
  3274. toggleFwField('natstate', true);
  3275. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3276. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3277. } else {
  3278. toggleFwField('natstate', false);
  3279. }
  3280. // Advanced tab fields
  3281. setFwFieldVal('layer7', r.layer7_protocol, false);
  3282. setFwFieldVal('content', r.content, false);
  3283. setFwFieldVal('connbytes', r.connection_bytes, false);
  3284. setFwFieldVal('connrate', r.connection_rate, false);
  3285. setFwFieldVal('pcc', r.pcc, false);
  3286. setFwFieldVal('srcmac', r.src_mac_address, true);
  3287. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3288. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3289. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3290. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3291. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3292. setFwFieldVal('tlshost', r.tls_host, false);
  3293. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3294. setFwFieldVal('priority', r.priority, false);
  3295. setFwFieldVal('dscp', r.dscp, false);
  3296. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3297. if (r.tos) {
  3298. const tosEl = document.getElementById('fw-val-tos');
  3299. if (tosEl) tosEl.value = r.tos;
  3300. }
  3301. setFwFieldVal('pktsize', r.packet_size, false);
  3302. setFwFieldVal('random', r.random, false);
  3303. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3304. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3305. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3306. setFwFieldVal('ttl', r.ttl, false);
  3307. // Extra tab fields
  3308. setFwFieldVal('time', r.time, false);
  3309. if (r.days) {
  3310. toggleFwField('days', true);
  3311. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3312. const chk = document.getElementById(`fw-day-${d}`);
  3313. if (chk) chk.checked = r.days.includes(d);
  3314. });
  3315. } else {
  3316. toggleFwField('days', false);
  3317. }
  3318. setFwFieldVal('limit', r.limit, false);
  3319. setFwFieldVal('dstlimit', r.dst_limit, false);
  3320. setFwFieldVal('psd', r.psd, false);
  3321. // Action fields
  3322. if (r.reject_with) {
  3323. const rwEl = document.getElementById('filter-modal-rejectwith');
  3324. if (rwEl) rwEl.value = r.reject_with;
  3325. }
  3326. if (r.jump_target) {
  3327. const jtEl = document.getElementById('filter-modal-jumptarget');
  3328. if (jtEl) jtEl.value = r.jump_target;
  3329. }
  3330. if (r.address_list) {
  3331. const alEl = document.getElementById('filter-modal-action-addrlist');
  3332. if (alEl) alEl.value = r.address_list;
  3333. }
  3334. if (r.address_list_timeout) {
  3335. const toEl = document.getElementById('filter-modal-action-timeout');
  3336. if (toEl) toEl.value = r.address_list_timeout;
  3337. }
  3338. setFwFieldVal('logprefix', r.log_prefix, false);
  3339. // Statistics
  3340. const bEl = document.getElementById('fw-stat-bytes');
  3341. const pEl = document.getElementById('fw-stat-packets');
  3342. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3343. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3344. state.fwLastBytes = r.bytes || 0;
  3345. state.fwLastPackets = r.packets || 0;
  3346. state.fwLastTimestamp = Date.now();
  3347. state.fwStatRateHistory = new Array(30).fill(0);
  3348. state.fwStatPktHistory = new Array(30).fill(0);
  3349. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3350. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3351. toggleFilterActionFields();
  3352. document.getElementById('filter-modal').classList.remove('hidden');
  3353. }
  3354. function closeFilterModal() {
  3355. stopFwStatPolling();
  3356. document.getElementById('filter-modal').classList.add('hidden');
  3357. }
  3358. function toggleFilterActionFields() {
  3359. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3360. const rejectBox = document.getElementById('filter-action-reject-box');
  3361. const jumpBox = document.getElementById('filter-action-jump-box');
  3362. const addrBox = document.getElementById('filter-action-addrlist-box');
  3363. if (rejectBox) {
  3364. if (act === 'reject') rejectBox.classList.remove('hidden');
  3365. else rejectBox.classList.add('hidden');
  3366. }
  3367. if (jumpBox) {
  3368. if (act === 'jump') jumpBox.classList.remove('hidden');
  3369. else jumpBox.classList.add('hidden');
  3370. }
  3371. if (addrBox) {
  3372. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3373. addrBox.classList.remove('hidden');
  3374. } else {
  3375. addrBox.classList.add('hidden');
  3376. }
  3377. }
  3378. if (act === 'log') {
  3379. const logEl = document.getElementById('filter-modal-log');
  3380. if (logEl) logEl.checked = true;
  3381. toggleFwField('logprefix', true);
  3382. }
  3383. }
  3384. function toggleFwLogPrefix() {
  3385. const isLog = document.getElementById('filter-modal-log')?.checked;
  3386. toggleFwField('logprefix', !!isLog);
  3387. }
  3388. function copyFilterRule() {
  3389. document.getElementById('filter-modal-id').value = '';
  3390. const badge = document.getElementById('fw-modal-badge');
  3391. if (badge) badge.innerText = 'New...';
  3392. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3393. }
  3394. function resetCurrentRuleCounters() {
  3395. state.fwStatRateHistory = new Array(30).fill(0);
  3396. state.fwStatPktHistory = new Array(30).fill(0);
  3397. state.fwLastBytes = 0;
  3398. state.fwLastPackets = 0;
  3399. state.fwLastTimestamp = Date.now();
  3400. const bEl = document.getElementById('fw-stat-bytes');
  3401. const pEl = document.getElementById('fw-stat-packets');
  3402. const rEl = document.getElementById('fw-stat-rate');
  3403. const prEl = document.getElementById('fw-stat-pktrate');
  3404. if (bEl) bEl.value = '0 B';
  3405. if (pEl) pEl.value = '0';
  3406. if (rEl) rEl.value = '0 bps';
  3407. if (prEl) prEl.value = '0 p/s';
  3408. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3409. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3410. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3411. }
  3412. async function resetAllFwCounters() {
  3413. try {
  3414. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3415. if (res.ok) {
  3416. resetCurrentRuleCounters();
  3417. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3418. loadFirewall(false);
  3419. }
  3420. } catch (err) {
  3421. showToast('Error', err.message, 'error');
  3422. }
  3423. }
  3424. async function applyFilterRule(closeAfter = false) {
  3425. const id = document.getElementById('filter-modal-id').value;
  3426. const chain = document.getElementById('filter-modal-chain').value;
  3427. const action = document.getElementById('filter-modal-action').value;
  3428. const comment = document.getElementById('filter-modal-comment').value.trim();
  3429. const enabled = document.getElementById('filter-modal-enabled').checked;
  3430. const src = getFwFieldVal('src', true);
  3431. const dst = getFwFieldVal('dst', true);
  3432. const srclist = getFwFieldVal('srclist', true);
  3433. const dstlist = getFwFieldVal('dstlist', true);
  3434. const srcgeo = getFwFieldVal('srcgeo', true);
  3435. const dstgeo = getFwFieldVal('dstgeo', true);
  3436. const proto = getFwFieldVal('proto', true);
  3437. const sport = getFwFieldVal('sport', true);
  3438. const dport = getFwFieldVal('dport', true);
  3439. const anyport = getFwFieldVal('anyport', true);
  3440. const iniface = getFwFieldVal('iniface', true);
  3441. const outiface = getFwFieldVal('outiface', true);
  3442. const inifacelist = getFwFieldVal('inifacelist', true);
  3443. const outifacelist = getFwFieldVal('outifacelist', true);
  3444. const pktmark = getFwFieldVal('pktmark', true);
  3445. const connmark = getFwFieldVal('connmark', true);
  3446. const routingmark = getFwFieldVal('routingmark', true);
  3447. const conntype = getFwFieldVal('conntype', false);
  3448. const states = [];
  3449. const csBox = document.getElementById('fw-field-cs');
  3450. if (csBox && !csBox.classList.contains('hidden')) {
  3451. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3452. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3453. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3454. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3455. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3456. }
  3457. const natStates = [];
  3458. const natBox = document.getElementById('fw-field-natstate');
  3459. if (natBox && !natBox.classList.contains('hidden')) {
  3460. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3461. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3462. }
  3463. const payload = {
  3464. id,
  3465. chain,
  3466. action,
  3467. protocol: proto || 'all',
  3468. src_address: src,
  3469. dst_address: dst,
  3470. src_port: sport,
  3471. dst_port: dport,
  3472. any_port: anyport,
  3473. in_interface: iniface,
  3474. out_interface: outiface,
  3475. in_interface_list: inifacelist,
  3476. out_interface_list: outifacelist,
  3477. packet_mark: pktmark,
  3478. connection_mark: connmark,
  3479. routing_mark: routingmark,
  3480. connection_type: conntype,
  3481. connection_state: states,
  3482. connection_nat_state: natStates,
  3483. src_address_list: srclist,
  3484. dst_address_list: dstlist,
  3485. src_geoip: srcgeo,
  3486. dst_geoip: dstgeo,
  3487. comment,
  3488. disabled: !enabled,
  3489. // Advanced tab
  3490. layer7_protocol: getFwFieldVal('layer7', false),
  3491. content: getFwFieldVal('content', false),
  3492. connection_bytes: getFwFieldVal('connbytes', false),
  3493. connection_rate: getFwFieldVal('connrate', false),
  3494. pcc: getFwFieldVal('pcc', false),
  3495. src_mac_address: getFwFieldVal('srcmac', true),
  3496. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3497. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3498. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3499. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3500. ipsec_policy: getFwFieldVal('ipsec', false),
  3501. tls_host: getFwFieldVal('tlshost', false),
  3502. ingress_priority: getFwFieldVal('ingresspriority', false),
  3503. priority: getFwFieldVal('priority', false),
  3504. dscp: getFwFieldVal('dscp', false),
  3505. tcp_mss: getFwFieldVal('tcpmss', false),
  3506. tos: document.getElementById('fw-val-tos')?.value || '',
  3507. packet_size: getFwFieldVal('pktsize', false),
  3508. random: getFwFieldVal('random', false),
  3509. tcp_flags: getFwFieldVal('tcpflags', false),
  3510. icmp_options: getFwFieldVal('icmpoptions', false),
  3511. ipv4_options: getFwFieldVal('ipv4options', false),
  3512. ttl: getFwFieldVal('ttl', false),
  3513. // Extra tab
  3514. time: getFwFieldVal('time', false),
  3515. limit: getFwFieldVal('limit', false),
  3516. dst_limit: getFwFieldVal('dstlimit', false),
  3517. psd: getFwFieldVal('psd', false),
  3518. // Action tab
  3519. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3520. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3521. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3522. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3523. log: document.getElementById('filter-modal-log')?.checked || false,
  3524. log_prefix: getFwFieldVal('logprefix', false)
  3525. };
  3526. try {
  3527. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3528. method: 'POST',
  3529. headers: { 'Content-Type': 'application/json' },
  3530. body: JSON.stringify(payload)
  3531. });
  3532. if (res.ok) {
  3533. const data = await res.json();
  3534. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3535. loadFirewall(false);
  3536. if (closeAfter) {
  3537. closeFilterModal();
  3538. } else {
  3539. if (data.id) {
  3540. document.getElementById('filter-modal-id').value = data.id;
  3541. const badge = document.getElementById('fw-modal-badge');
  3542. if (badge) badge.innerText = `#${data.id}`;
  3543. }
  3544. }
  3545. } else {
  3546. const err = await res.json();
  3547. showToast('Error', err.message || 'Failed to save rule', 'error');
  3548. }
  3549. } catch (err) {
  3550. showToast('Error', err.message, 'error');
  3551. }
  3552. }
  3553. function submitSaveFilterRule(e) {
  3554. if (e && e.preventDefault) e.preventDefault();
  3555. return applyFilterRule(true);
  3556. }
  3557. function startFwStatPolling() {
  3558. stopFwStatPolling();
  3559. pollRuleStats();
  3560. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3561. }
  3562. function stopFwStatPolling() {
  3563. if (state.fwStatInterval) {
  3564. clearInterval(state.fwStatInterval);
  3565. state.fwStatInterval = null;
  3566. }
  3567. }
  3568. async function pollRuleStats() {
  3569. const id = document.getElementById('filter-modal-id')?.value;
  3570. if (!id) {
  3571. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3572. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3573. return;
  3574. }
  3575. try {
  3576. const res = await fetch(`${API_BASE}/firewall/filter`);
  3577. if (!res.ok) return;
  3578. const rules = await res.json();
  3579. const r = rules.find(x => x.id === id);
  3580. if (!r) return;
  3581. const now = Date.now();
  3582. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3583. state.fwLastTimestamp = now;
  3584. const curBytes = r.bytes || 0;
  3585. const curPackets = r.packets || 0;
  3586. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3587. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3588. state.fwLastBytes = curBytes;
  3589. state.fwLastPackets = curPackets;
  3590. const rateBps = Math.round((deltaBytes * 8) / dt);
  3591. const ratePkt = Math.round(deltaPkts / dt);
  3592. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3593. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3594. state.fwStatRateHistory.push(rateBps);
  3595. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3596. state.fwStatPktHistory.push(ratePkt);
  3597. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3598. const bEl = document.getElementById('fw-stat-bytes');
  3599. const pEl = document.getElementById('fw-stat-packets');
  3600. const rEl = document.getElementById('fw-stat-rate');
  3601. const prEl = document.getElementById('fw-stat-pktrate');
  3602. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3603. if (pEl) pEl.value = curPackets.toLocaleString();
  3604. if (rEl) rEl.value = formatBps(rateBps);
  3605. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3606. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3607. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3608. } catch (e) {
  3609. console.error('Error polling rule stats', e);
  3610. }
  3611. }
  3612. function formatBps(bps) {
  3613. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3614. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3615. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3616. return bps + ' bps';
  3617. }
  3618. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3619. const svg = document.getElementById(svgId);
  3620. if (!svg) return;
  3621. const w = 500;
  3622. const h = 100;
  3623. const paddingRight = 45;
  3624. const graphWidth = w - paddingRight;
  3625. const maxVal = Math.max(5, ...dataArray);
  3626. const currentVal = dataArray[dataArray.length - 1] || 0;
  3627. const leg = document.getElementById(legendId);
  3628. if (leg) {
  3629. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3630. }
  3631. let gridLines = '';
  3632. for (let i = 0; i <= 5; i++) {
  3633. const y = 8 + (i * (h - 18) / 5);
  3634. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3635. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3636. gridLines += `
  3637. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3638. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3639. `;
  3640. }
  3641. const step = graphWidth / (dataArray.length - 1);
  3642. const points = dataArray.map((val, idx) => {
  3643. const x = idx * step;
  3644. const y = (h - 10) - (val / maxVal) * (h - 20);
  3645. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3646. });
  3647. const polylineStr = points.join(' ');
  3648. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3649. svg.innerHTML = `
  3650. ${gridLines}
  3651. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3652. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3653. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3654. `;
  3655. }
  3656. async function moveFilterRule(id, dir) {
  3657. try {
  3658. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3659. method: 'POST',
  3660. headers: { 'Content-Type': 'application/json' },
  3661. body: JSON.stringify({ direction: dir })
  3662. });
  3663. if (res.ok) loadFirewall(false);
  3664. } catch (err) {
  3665. showToast('Error', err.message, 'error');
  3666. }
  3667. }
  3668. async function toggleFilterRuleState(id, disabled) {
  3669. try {
  3670. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3671. method: 'POST',
  3672. headers: { 'Content-Type': 'application/json' },
  3673. body: JSON.stringify({ disabled })
  3674. });
  3675. if (res.ok) loadFirewall(false);
  3676. } catch (err) {
  3677. showToast('Error', err.message, 'error');
  3678. }
  3679. }
  3680. async function deleteFilterRule(id) {
  3681. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3682. try {
  3683. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3684. if (res.ok) {
  3685. showToast('Deleted', 'Filter rule removed', 'success');
  3686. loadFirewall(false);
  3687. }
  3688. } catch (err) {
  3689. showToast('Error', err.message, 'error');
  3690. }
  3691. }
  3692. // ----------------- NAT Rules -----------------
  3693. function renderNATRules() {
  3694. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3695. const tbody = document.getElementById('nat-table-body');
  3696. const empty = document.getElementById('nat-empty');
  3697. if (!tbody) return;
  3698. tbody.innerHTML = '';
  3699. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3700. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3701. if (rules.length === 0) {
  3702. empty?.classList.remove('hidden');
  3703. return;
  3704. }
  3705. empty?.classList.add('hidden');
  3706. rules.forEach((r, idx) => {
  3707. const tr = document.createElement('tr');
  3708. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3709. let toTarget = '-';
  3710. if (r.action === 'jump') {
  3711. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3712. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3713. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3714. } else if (r.action === 'redirect') {
  3715. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3716. } else if (r.action === 'masquerade') {
  3717. 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>`;
  3718. } else if (r.action === 'log') {
  3719. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3720. } else {
  3721. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3722. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3723. }
  3724. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3725. tr.innerHTML = `
  3726. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3727. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3728. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3729. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3730. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3731. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3732. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3733. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3734. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3735. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3736. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3737. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3738. </td>
  3739. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3740. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3741. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3742. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3743. <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>
  3744. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3745. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3746. </td>
  3747. `;
  3748. tbody.appendChild(tr);
  3749. });
  3750. }
  3751. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3752. function switchNATRuleTab(tab) {
  3753. state.activeNATRuleTab = tab;
  3754. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3755. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3756. btn.classList.add('text-slate-400', 'border-transparent');
  3757. });
  3758. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3759. if (activeBtn) {
  3760. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3761. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3762. }
  3763. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3764. const activePane = document.getElementById(`nat-pane-${tab}`);
  3765. if (activePane) activePane.classList.remove('hidden');
  3766. if (tab === 'statistics') {
  3767. startNATStatPolling();
  3768. } else {
  3769. stopNATStatPolling();
  3770. }
  3771. }
  3772. function toggleNATField(fieldKey, expand) {
  3773. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3774. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3775. if (!plusBtn || !fieldBox) return;
  3776. if (expand) {
  3777. plusBtn.classList.add('hidden');
  3778. fieldBox.classList.remove('hidden');
  3779. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3780. if (valInput) valInput.focus();
  3781. } else {
  3782. fieldBox.classList.add('hidden');
  3783. plusBtn.classList.remove('hidden');
  3784. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3785. if (valInput) {
  3786. if (valInput.tagName === 'SELECT') {
  3787. valInput.selectedIndex = 0;
  3788. } else {
  3789. valInput.value = '';
  3790. }
  3791. }
  3792. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3793. if (invInput) invInput.checked = false;
  3794. if (fieldKey === 'days') {
  3795. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3796. const el = document.getElementById(`nat-day-${d}`);
  3797. if (el) el.checked = true;
  3798. });
  3799. }
  3800. }
  3801. }
  3802. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3803. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3804. toggleNATField(fieldKey, true);
  3805. let strVal = String(value);
  3806. if (hasInvert) {
  3807. const inv = strVal.startsWith('!');
  3808. if (inv) strVal = strVal.slice(1);
  3809. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3810. if (invEl) invEl.checked = inv;
  3811. }
  3812. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3813. if (valEl) valEl.value = strVal;
  3814. } else {
  3815. toggleNATField(fieldKey, false);
  3816. }
  3817. }
  3818. function getNATFieldVal(fieldKey, hasInvert = false) {
  3819. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3820. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3821. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3822. let v = valEl ? valEl.value.trim() : '';
  3823. if (!v) return '';
  3824. if (hasInvert) {
  3825. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3826. if (invEl && invEl.checked) {
  3827. v = '!' + v.replace(/^!/, '');
  3828. }
  3829. }
  3830. return v;
  3831. }
  3832. function toggleMaximizeNATModal() {
  3833. const win = document.getElementById('nat-modal-window');
  3834. if (!win) return;
  3835. if (win.classList.contains('max-w-[720px]')) {
  3836. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3837. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3838. } else {
  3839. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3840. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3841. }
  3842. }
  3843. function handleNATChainChange() {
  3844. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3845. const actSel = document.getElementById('nat-modal-action');
  3846. if (actSel) {
  3847. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3848. actSel.value = 'masquerade';
  3849. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3850. actSel.value = 'dst-nat';
  3851. }
  3852. }
  3853. toggleNATActionFields();
  3854. }
  3855. function toggleNATActionFields() {
  3856. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3857. const rowAddr = document.getElementById('nat-row-toaddr');
  3858. const rowPort = document.getElementById('nat-row-toport');
  3859. const jumpBox = document.getElementById('nat-action-jump-box');
  3860. const addrBox = document.getElementById('nat-action-addrlist-box');
  3861. // Hide all dynamic rows first
  3862. if (rowAddr) rowAddr.classList.add('hidden');
  3863. if (rowPort) rowPort.classList.add('hidden');
  3864. if (jumpBox) jumpBox.classList.add('hidden');
  3865. if (addrBox) addrBox.classList.add('hidden');
  3866. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3867. if (rowAddr) rowAddr.classList.remove('hidden');
  3868. if (rowPort) rowPort.classList.remove('hidden');
  3869. } else if (act === 'redirect' || act === 'masquerade') {
  3870. if (rowPort) rowPort.classList.remove('hidden');
  3871. } else if (act === 'jump') {
  3872. if (jumpBox) jumpBox.classList.remove('hidden');
  3873. } else if (act.includes('address-list') || act.includes('address list')) {
  3874. if (addrBox) addrBox.classList.remove('hidden');
  3875. }
  3876. if (act === 'log') {
  3877. const logEl = document.getElementById('nat-modal-log');
  3878. if (logEl) logEl.checked = true;
  3879. toggleNATField('logprefix', true);
  3880. }
  3881. }
  3882. function toggleNATLogPrefix() {
  3883. const isLog = document.getElementById('nat-modal-log')?.checked;
  3884. toggleNATField('logprefix', !!isLog);
  3885. }
  3886. function openAddNATModal() {
  3887. switchNATRuleTab('general');
  3888. const badge = document.getElementById('nat-modal-badge');
  3889. if (badge) badge.innerText = 'New...';
  3890. document.getElementById('nat-modal-id').value = '';
  3891. document.getElementById('nat-modal-enabled').checked = true;
  3892. document.getElementById('nat-modal-comment').value = '';
  3893. document.getElementById('nat-modal-chain').value = 'srcnat';
  3894. document.getElementById('nat-modal-action').value = 'masquerade';
  3895. document.getElementById('nat-modal-toaddr').value = '';
  3896. document.getElementById('nat-modal-toport').value = '';
  3897. document.getElementById('nat-modal-log').checked = false;
  3898. populateInterfaceSelect('nat-val-iniface');
  3899. populateInterfaceSelect('nat-val-outiface');
  3900. populateAddressListSelect('nat-val-srclist');
  3901. populateAddressListSelect('nat-val-dstlist');
  3902. populateGeoIPSelect('nat-val-srcgeo');
  3903. populateGeoIPSelect('nat-val-dstgeo');
  3904. const allFieldKeys = [
  3905. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3906. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3907. 'routingmark', 'conntype',
  3908. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3909. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3910. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3911. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3912. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3913. ];
  3914. allFieldKeys.forEach(k => toggleNATField(k, false));
  3915. resetCurrentNATRuleCounters();
  3916. toggleNATActionFields();
  3917. document.getElementById('nat-modal').classList.remove('hidden');
  3918. }
  3919. function openEditNATModal(id) {
  3920. const r = (state.natRules || []).find(rule => rule.id === id);
  3921. if (!r) return;
  3922. switchNATRuleTab('general');
  3923. const badge = document.getElementById('nat-modal-badge');
  3924. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3925. document.getElementById('nat-modal-id').value = r.id;
  3926. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3927. document.getElementById('nat-modal-comment').value = r.comment || '';
  3928. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3929. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3930. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3931. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3932. document.getElementById('nat-modal-log').checked = !!r.log;
  3933. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3934. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3935. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3936. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3937. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3938. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3939. setNATFieldVal('src', r.src_address, true);
  3940. setNATFieldVal('dst', r.dst_address, true);
  3941. setNATFieldVal('srclist', r.src_address_list, true);
  3942. setNATFieldVal('dstlist', r.dst_address_list, true);
  3943. setNATFieldVal('srcgeo', r.src_geoip, true);
  3944. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3945. if (r.protocol && r.protocol !== 'all') {
  3946. setNATFieldVal('proto', r.protocol, true);
  3947. } else {
  3948. toggleNATField('proto', false);
  3949. }
  3950. setNATFieldVal('sport', r.src_port, true);
  3951. setNATFieldVal('dport', r.dst_port, true);
  3952. setNATFieldVal('anyport', r.any_port, true);
  3953. setNATFieldVal('iniface', r.in_interface, true);
  3954. setNATFieldVal('outiface', r.out_interface, true);
  3955. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3956. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3957. setNATFieldVal('pktmark', r.packet_mark, true);
  3958. setNATFieldVal('connmark', r.connection_mark, true);
  3959. setNATFieldVal('routingmark', r.routing_mark, true);
  3960. setNATFieldVal('conntype', r.connection_type, false);
  3961. // Advanced tab fields
  3962. setNATFieldVal('layer7', r.layer7_protocol, false);
  3963. setNATFieldVal('content', r.content, false);
  3964. setNATFieldVal('connbytes', r.connection_bytes, false);
  3965. setNATFieldVal('connrate', r.connection_rate, false);
  3966. setNATFieldVal('pcc', r.pcc, false);
  3967. setNATFieldVal('srcmac', r.src_mac_address, true);
  3968. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3969. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3970. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3971. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3972. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3973. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3974. setNATFieldVal('priority', r.priority, false);
  3975. setNATFieldVal('dscp', r.dscp, false);
  3976. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3977. if (r.tos) {
  3978. const tosEl = document.getElementById('nat-val-tos');
  3979. if (tosEl) tosEl.value = r.tos;
  3980. }
  3981. setNATFieldVal('pktsize', r.packet_size, false);
  3982. setNATFieldVal('random', r.random, false);
  3983. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3984. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3985. setNATFieldVal('ttl', r.ttl, false);
  3986. // Extra tab fields
  3987. setNATFieldVal('time', r.time, false);
  3988. if (r.days) {
  3989. toggleNATField('days', true);
  3990. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3991. const chk = document.getElementById(`nat-day-${d}`);
  3992. if (chk) chk.checked = r.days.includes(d);
  3993. });
  3994. } else {
  3995. toggleNATField('days', false);
  3996. }
  3997. setNATFieldVal('limit', r.limit, false);
  3998. setNATFieldVal('dstlimit', r.dst_limit, false);
  3999. setNATFieldVal('psd', r.psd, false);
  4000. // Action fields
  4001. if (r.jump_target) {
  4002. const jtEl = document.getElementById('nat-modal-jumptarget');
  4003. if (jtEl) jtEl.value = r.jump_target;
  4004. }
  4005. if (r.address_list) {
  4006. const alEl = document.getElementById('nat-modal-action-addrlist');
  4007. if (alEl) alEl.value = r.address_list;
  4008. }
  4009. if (r.address_list_timeout) {
  4010. const toEl = document.getElementById('nat-modal-action-timeout');
  4011. if (toEl) toEl.value = r.address_list_timeout;
  4012. }
  4013. setNATFieldVal('logprefix', r.log_prefix, false);
  4014. // Statistics
  4015. const bEl = document.getElementById('nat-stat-bytes');
  4016. const pEl = document.getElementById('nat-stat-packets');
  4017. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4018. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4019. state.natLastBytes = r.bytes || 0;
  4020. state.natLastPackets = r.packets || 0;
  4021. state.natLastTimestamp = Date.now();
  4022. state.natStatRateHistory = new Array(30).fill(0);
  4023. state.natStatPktHistory = new Array(30).fill(0);
  4024. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4025. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4026. toggleNATActionFields();
  4027. document.getElementById('nat-modal').classList.remove('hidden');
  4028. }
  4029. function closeNATModal() {
  4030. stopNATStatPolling();
  4031. document.getElementById('nat-modal').classList.add('hidden');
  4032. }
  4033. function copyNATRule() {
  4034. document.getElementById('nat-modal-id').value = '';
  4035. const badge = document.getElementById('nat-modal-badge');
  4036. if (badge) badge.innerText = 'New...';
  4037. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4038. }
  4039. function resetCurrentNATRuleCounters() {
  4040. state.natStatRateHistory = new Array(30).fill(0);
  4041. state.natStatPktHistory = new Array(30).fill(0);
  4042. state.natLastBytes = 0;
  4043. state.natLastPackets = 0;
  4044. state.natLastTimestamp = Date.now();
  4045. const bEl = document.getElementById('nat-stat-bytes');
  4046. const pEl = document.getElementById('nat-stat-packets');
  4047. const rEl = document.getElementById('nat-stat-rate');
  4048. const prEl = document.getElementById('nat-stat-pktrate');
  4049. if (bEl) bEl.value = '0 B';
  4050. if (pEl) pEl.value = '0';
  4051. if (rEl) rEl.value = '0 bps';
  4052. if (prEl) prEl.value = '0 p/s';
  4053. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4054. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4055. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4056. }
  4057. async function applyNATRule(closeAfter = false) {
  4058. const id = document.getElementById('nat-modal-id').value;
  4059. const chain = document.getElementById('nat-modal-chain').value;
  4060. const action = document.getElementById('nat-modal-action').value;
  4061. const comment = document.getElementById('nat-modal-comment').value.trim();
  4062. const enabled = document.getElementById('nat-modal-enabled').checked;
  4063. const src = getNATFieldVal('src', true);
  4064. const dst = getNATFieldVal('dst', true);
  4065. const srclist = getNATFieldVal('srclist', true);
  4066. const dstlist = getNATFieldVal('dstlist', true);
  4067. const srcgeo = getNATFieldVal('srcgeo', true);
  4068. const dstgeo = getNATFieldVal('dstgeo', true);
  4069. const proto = getNATFieldVal('proto', true);
  4070. const sport = getNATFieldVal('sport', true);
  4071. const dport = getNATFieldVal('dport', true);
  4072. const anyport = getNATFieldVal('anyport', true);
  4073. const iniface = getNATFieldVal('iniface', true);
  4074. const outiface = getNATFieldVal('outiface', true);
  4075. const inifacelist = getNATFieldVal('inifacelist', true);
  4076. const outifacelist = getNATFieldVal('outifacelist', true);
  4077. const pktmark = getNATFieldVal('pktmark', true);
  4078. const connmark = getNATFieldVal('connmark', true);
  4079. const routingmark = getNATFieldVal('routingmark', true);
  4080. const conntype = getNATFieldVal('conntype', false);
  4081. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4082. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4083. const payload = {
  4084. id,
  4085. chain,
  4086. action,
  4087. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4088. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4089. protocol: proto || 'all',
  4090. src_address: src,
  4091. dst_address: dst,
  4092. src_port: sport,
  4093. dst_port: dport,
  4094. any_port: anyport,
  4095. in_interface: iniface,
  4096. out_interface: outiface,
  4097. in_interface_list: inifacelist,
  4098. out_interface_list: outifacelist,
  4099. packet_mark: pktmark,
  4100. connection_mark: connmark,
  4101. routing_mark: routingmark,
  4102. connection_type: conntype,
  4103. src_address_list: srclist,
  4104. dst_address_list: dstlist,
  4105. src_geoip: srcgeo,
  4106. dst_geoip: dstgeo,
  4107. comment,
  4108. disabled: !enabled,
  4109. // Advanced tab
  4110. layer7_protocol: getNATFieldVal('layer7', false),
  4111. content: getNATFieldVal('content', false),
  4112. connection_bytes: getNATFieldVal('connbytes', false),
  4113. connection_rate: getNATFieldVal('connrate', false),
  4114. pcc: getNATFieldVal('pcc', false),
  4115. src_mac_address: getNATFieldVal('srcmac', true),
  4116. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4117. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4118. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4119. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4120. ipsec_policy: getNATFieldVal('ipsec', false),
  4121. ingress_priority: getNATFieldVal('ingresspriority', false),
  4122. priority: getNATFieldVal('priority', false),
  4123. dscp: getNATFieldVal('dscp', false),
  4124. tcp_mss: getNATFieldVal('tcpmss', false),
  4125. tos: document.getElementById('nat-val-tos')?.value || '',
  4126. packet_size: getNATFieldVal('pktsize', false),
  4127. random: getNATFieldVal('random', false),
  4128. icmp_options: getNATFieldVal('icmpoptions', false),
  4129. ipv4_options: getNATFieldVal('ipv4options', false),
  4130. ttl: getNATFieldVal('ttl', false),
  4131. // Extra tab
  4132. time: getNATFieldVal('time', false),
  4133. limit: getNATFieldVal('limit', false),
  4134. dst_limit: getNATFieldVal('dstlimit', false),
  4135. psd: getNATFieldVal('psd', false),
  4136. // Action tab
  4137. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4138. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4139. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4140. log: document.getElementById('nat-modal-log')?.checked || false,
  4141. log_prefix: getNATFieldVal('logprefix', false)
  4142. };
  4143. try {
  4144. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4145. method: 'POST',
  4146. headers: { 'Content-Type': 'application/json' },
  4147. body: JSON.stringify(payload)
  4148. });
  4149. if (res.ok) {
  4150. const data = await res.json();
  4151. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4152. loadFirewall(false);
  4153. if (closeAfter) {
  4154. closeNATModal();
  4155. } else {
  4156. if (data.id) {
  4157. document.getElementById('nat-modal-id').value = data.id;
  4158. const badge = document.getElementById('nat-modal-badge');
  4159. if (badge) badge.innerText = `#${data.id}`;
  4160. }
  4161. }
  4162. } else {
  4163. const err = await res.json();
  4164. showToast('Error', err.message || 'Failed to save rule', 'error');
  4165. }
  4166. } catch (err) {
  4167. showToast('Error', err.message, 'error');
  4168. }
  4169. }
  4170. function submitSaveNATRule(e) {
  4171. if (e && e.preventDefault) e.preventDefault();
  4172. return applyNATRule(true);
  4173. }
  4174. function startNATStatPolling() {
  4175. stopNATStatPolling();
  4176. pollNATRuleStats();
  4177. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4178. }
  4179. function stopNATStatPolling() {
  4180. if (state.natStatInterval) {
  4181. clearInterval(state.natStatInterval);
  4182. state.natStatInterval = null;
  4183. }
  4184. }
  4185. async function pollNATRuleStats() {
  4186. const id = document.getElementById('nat-modal-id')?.value;
  4187. if (!id) {
  4188. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4189. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4190. return;
  4191. }
  4192. try {
  4193. const res = await fetch(`${API_BASE}/firewall/nat`);
  4194. if (!res.ok) return;
  4195. const rules = await res.json();
  4196. const r = rules.find(x => x.id === id);
  4197. if (!r) return;
  4198. const now = Date.now();
  4199. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4200. state.natLastTimestamp = now;
  4201. const curBytes = r.bytes || 0;
  4202. const curPackets = r.packets || 0;
  4203. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4204. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4205. state.natLastBytes = curBytes;
  4206. state.natLastPackets = curPackets;
  4207. const rateBps = Math.round((deltaBytes * 8) / dt);
  4208. const ratePkt = Math.round(deltaPkts / dt);
  4209. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4210. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4211. state.natStatRateHistory.push(rateBps);
  4212. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4213. state.natStatPktHistory.push(ratePkt);
  4214. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4215. const bEl = document.getElementById('nat-stat-bytes');
  4216. const pEl = document.getElementById('nat-stat-packets');
  4217. const rEl = document.getElementById('nat-stat-rate');
  4218. const prEl = document.getElementById('nat-stat-pktrate');
  4219. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4220. if (pEl) pEl.value = curPackets.toLocaleString();
  4221. if (rEl) rEl.value = formatBps(rateBps);
  4222. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4223. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4224. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4225. } catch (e) {
  4226. console.error('Error polling NAT rule stats', e);
  4227. }
  4228. }
  4229. async function moveNATRule(id, dir) {
  4230. try {
  4231. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4232. method: 'POST',
  4233. headers: { 'Content-Type': 'application/json' },
  4234. body: JSON.stringify({ direction: dir })
  4235. });
  4236. if (res.ok) loadFirewall(false);
  4237. } catch (err) {
  4238. showToast('Error', err.message, 'error');
  4239. }
  4240. }
  4241. async function toggleNATRuleState(id, disabled) {
  4242. try {
  4243. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4244. method: 'POST',
  4245. headers: { 'Content-Type': 'application/json' },
  4246. body: JSON.stringify({ disabled })
  4247. });
  4248. if (res.ok) loadFirewall(false);
  4249. } catch (err) {
  4250. showToast('Error', err.message, 'error');
  4251. }
  4252. }
  4253. async function deleteNATRule(id) {
  4254. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4255. try {
  4256. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4257. if (res.ok) {
  4258. showToast('Deleted', 'NAT rule removed', 'success');
  4259. loadFirewall(false);
  4260. }
  4261. } catch (err) {
  4262. showToast('Error', err.message, 'error');
  4263. }
  4264. }
  4265. // ----------------- Mangle Rules -----------------
  4266. function renderMangleRules() {
  4267. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4268. const tbody = document.getElementById('mangle-table-body');
  4269. const empty = document.getElementById('mangle-empty');
  4270. if (!tbody) return;
  4271. tbody.innerHTML = '';
  4272. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4273. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4274. if (rules.length === 0) {
  4275. empty?.classList.remove('hidden');
  4276. return;
  4277. }
  4278. empty?.classList.add('hidden');
  4279. rules.forEach((r, idx) => {
  4280. const tr = document.createElement('tr');
  4281. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4282. let markVal = '<span class="text-slate-500">-</span>';
  4283. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4284. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4285. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4286. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4287. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4288. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4289. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4290. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4291. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4292. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4293. 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>`;
  4294. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4295. tr.innerHTML = `
  4296. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4297. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4298. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4299. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4300. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4301. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4302. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4303. <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>
  4304. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4305. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4306. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4307. </td>
  4308. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4309. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4310. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4311. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4312. <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>
  4313. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4314. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4315. </td>
  4316. `;
  4317. tbody.appendChild(tr);
  4318. });
  4319. }
  4320. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4321. function switchMangleRuleTab(tab) {
  4322. state.activeMangleRuleTab = tab;
  4323. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4324. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4325. btn.classList.add('text-slate-400', 'border-transparent');
  4326. });
  4327. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4328. if (activeBtn) {
  4329. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4330. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4331. }
  4332. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4333. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4334. if (activePane) activePane.classList.remove('hidden');
  4335. if (tab === 'statistics') {
  4336. startMangleStatPolling();
  4337. } else {
  4338. stopMangleStatPolling();
  4339. }
  4340. }
  4341. function toggleMangleField(fieldKey, expand) {
  4342. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4343. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4344. if (!plusBtn || !fieldBox) return;
  4345. if (expand) {
  4346. plusBtn.classList.add('hidden');
  4347. fieldBox.classList.remove('hidden');
  4348. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4349. if (valInput) valInput.focus();
  4350. } else {
  4351. fieldBox.classList.add('hidden');
  4352. plusBtn.classList.remove('hidden');
  4353. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4354. if (valInput) {
  4355. if (valInput.tagName === 'SELECT') {
  4356. valInput.selectedIndex = 0;
  4357. } else {
  4358. valInput.value = '';
  4359. }
  4360. }
  4361. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4362. if (invInput) invInput.checked = false;
  4363. if (fieldKey === 'cs') {
  4364. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4365. const el = document.getElementById(id);
  4366. if (el) el.checked = false;
  4367. });
  4368. }
  4369. if (fieldKey === 'natstate') {
  4370. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4371. const el = document.getElementById(id);
  4372. if (el) el.checked = false;
  4373. });
  4374. }
  4375. }
  4376. }
  4377. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4378. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4379. toggleMangleField(fieldKey, true);
  4380. let strVal = String(value);
  4381. if (hasInvert) {
  4382. const inv = strVal.startsWith('!');
  4383. if (inv) strVal = strVal.slice(1);
  4384. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4385. if (invEl) invEl.checked = inv;
  4386. }
  4387. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4388. if (valEl) valEl.value = strVal;
  4389. } else {
  4390. toggleMangleField(fieldKey, false);
  4391. }
  4392. }
  4393. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4394. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4395. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4396. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4397. let v = valEl ? valEl.value.trim() : '';
  4398. if (!v) return '';
  4399. if (hasInvert) {
  4400. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4401. if (invEl && invEl.checked) {
  4402. v = '!' + v.replace(/^!/, '');
  4403. }
  4404. }
  4405. return v;
  4406. }
  4407. function toggleMaximizeMangleModal() {
  4408. const win = document.getElementById('mangle-modal-window');
  4409. if (!win) return;
  4410. if (win.classList.contains('max-w-[720px]')) {
  4411. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4412. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4413. } else {
  4414. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4415. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4416. }
  4417. }
  4418. function toggleMangleActionFields() {
  4419. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4420. // Hide all dynamic rows first
  4421. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4422. const el = document.getElementById(`mangle-row-${id}`);
  4423. if (el) el.classList.add('hidden');
  4424. });
  4425. const jumpBox = document.getElementById('mangle-action-jump-box');
  4426. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4427. if (jumpBox) jumpBox.classList.add('hidden');
  4428. if (addrBox) addrBox.classList.add('hidden');
  4429. // Activate matching rows
  4430. if (act === 'mark-connection') {
  4431. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4432. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4433. } else if (act === 'mark-routing') {
  4434. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4435. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4436. } else if (act === 'mark-packet') {
  4437. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4438. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4439. } else if (act === 'change-mss') {
  4440. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4441. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4442. } else if (act === 'change-dscp') {
  4443. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4444. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4445. } else if (act === 'change-ttl') {
  4446. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4447. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4448. } else if (act === 'set-priority') {
  4449. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4450. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4451. } else if (act === 'route') {
  4452. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4453. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4454. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4455. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4456. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4457. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4458. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4459. } else if (act === 'jump') {
  4460. if (jumpBox) jumpBox.classList.remove('hidden');
  4461. } else if (act.includes('address-list') || act.includes('address list')) {
  4462. if (addrBox) addrBox.classList.remove('hidden');
  4463. }
  4464. if (act === 'log') {
  4465. const logEl = document.getElementById('mangle-modal-log');
  4466. if (logEl) logEl.checked = true;
  4467. toggleMangleField('logprefix', true);
  4468. }
  4469. }
  4470. function toggleMangleLogPrefix() {
  4471. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4472. toggleMangleField('logprefix', !!isLog);
  4473. }
  4474. const allMangleFieldKeys = [
  4475. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4476. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4477. 'routingmark', 'conntype', 'cs', 'natstate',
  4478. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4479. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4480. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4481. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4482. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4483. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4484. ];
  4485. function openAddMangleModal() {
  4486. switchMangleRuleTab('general');
  4487. const badge = document.getElementById('mangle-modal-badge');
  4488. if (badge) badge.innerText = 'New...';
  4489. document.getElementById('mangle-modal-id').value = '';
  4490. document.getElementById('mangle-modal-enabled').checked = true;
  4491. document.getElementById('mangle-modal-comment').value = '';
  4492. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4493. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4494. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4495. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4496. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4497. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4498. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4499. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4500. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4501. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4502. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4503. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4504. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4505. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4506. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4507. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4508. populateInterfaceSelect('mangle-val-iniface');
  4509. populateInterfaceSelect('mangle-val-outiface');
  4510. populateAddressListSelect('mangle-val-srclist');
  4511. populateAddressListSelect('mangle-val-dstlist');
  4512. populateGeoIPSelect('mangle-val-srcgeo');
  4513. populateGeoIPSelect('mangle-val-dstgeo');
  4514. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4515. resetCurrentMangleRuleCounters();
  4516. toggleMangleActionFields();
  4517. document.getElementById('mangle-modal').classList.remove('hidden');
  4518. }
  4519. function openEditMangleModal(id) {
  4520. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4521. if (!r) return;
  4522. switchMangleRuleTab('general');
  4523. const badge = document.getElementById('mangle-modal-badge');
  4524. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4525. document.getElementById('mangle-modal-id').value = r.id;
  4526. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4527. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4528. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4529. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4530. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4531. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4532. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4533. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4534. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4535. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4536. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4537. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4538. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4539. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4540. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4541. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4542. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4543. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4544. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4545. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4546. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4547. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4548. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4549. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4550. setMangleFieldVal('src', r.src_address, true);
  4551. setMangleFieldVal('dst', r.dst_address, true);
  4552. setMangleFieldVal('srclist', r.src_address_list, true);
  4553. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4554. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4555. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4556. if (r.protocol && r.protocol !== 'all') {
  4557. setMangleFieldVal('proto', r.protocol, true);
  4558. } else {
  4559. toggleMangleField('proto', false);
  4560. }
  4561. setMangleFieldVal('sport', r.src_port, true);
  4562. setMangleFieldVal('dport', r.dst_port, true);
  4563. setMangleFieldVal('anyport', r.any_port, true);
  4564. setMangleFieldVal('iniface', r.in_interface, true);
  4565. setMangleFieldVal('outiface', r.out_interface, true);
  4566. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4567. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4568. setMangleFieldVal('pktmark', r.packet_mark, true);
  4569. setMangleFieldVal('connmark', r.connection_mark, true);
  4570. setMangleFieldVal('routingmark', r.routing_mark, true);
  4571. setMangleFieldVal('conntype', r.connection_type, false);
  4572. // Connection State
  4573. const states = r.connection_state || [];
  4574. if (states.length > 0) {
  4575. toggleMangleField('cs', true);
  4576. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4577. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4578. if (el) el.checked = states.includes(s);
  4579. });
  4580. } else {
  4581. toggleMangleField('cs', false);
  4582. }
  4583. // Connection NAT State
  4584. const natStates = r.connection_nat_state || [];
  4585. if (natStates.length > 0) {
  4586. toggleMangleField('natstate', true);
  4587. ['srcnat', 'dstnat'].forEach(s => {
  4588. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4589. if (el) el.checked = natStates.includes(s);
  4590. });
  4591. } else {
  4592. toggleMangleField('natstate', false);
  4593. }
  4594. // Advanced tab fields
  4595. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4596. setMangleFieldVal('content', r.content, false);
  4597. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4598. setMangleFieldVal('connrate', r.connection_rate, false);
  4599. setMangleFieldVal('pcc', r.pcc, false);
  4600. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4601. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4602. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4603. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4604. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4605. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4606. setMangleFieldVal('tlshost', r.tls_host, false);
  4607. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4608. setMangleFieldVal('priority', r.priority, false);
  4609. setMangleFieldVal('dscp', r.dscp, false);
  4610. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4611. if (r.tos) {
  4612. const tosEl = document.getElementById('mangle-val-tos');
  4613. if (tosEl) tosEl.value = r.tos;
  4614. }
  4615. setMangleFieldVal('pktsize', r.packet_size, false);
  4616. setMangleFieldVal('random', r.random, false);
  4617. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4618. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4619. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4620. setMangleFieldVal('ttl', r.ttl, false);
  4621. // Extra tab fields
  4622. setMangleFieldVal('nth', r.nth, false);
  4623. setMangleFieldVal('connlimit', r.connection_limit, false);
  4624. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4625. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4626. setMangleFieldVal('hotspot', r.hotspot, false);
  4627. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4628. setMangleFieldVal('limit', r.limit, false);
  4629. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4630. setMangleFieldVal('time', r.time, false);
  4631. setMangleFieldVal('psd', r.psd, false);
  4632. // Action fields
  4633. if (r.jump_target) {
  4634. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4635. if (jtEl) jtEl.value = r.jump_target;
  4636. }
  4637. if (r.address_list) {
  4638. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4639. if (alEl) alEl.value = r.address_list;
  4640. }
  4641. if (r.address_list_timeout) {
  4642. const toEl = document.getElementById('mangle-modal-action-timeout');
  4643. if (toEl) toEl.value = r.address_list_timeout;
  4644. }
  4645. setMangleFieldVal('logprefix', r.log_prefix, false);
  4646. // Statistics
  4647. const bEl = document.getElementById('mangle-stat-bytes');
  4648. const pEl = document.getElementById('mangle-stat-packets');
  4649. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4650. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4651. state.mangleLastBytes = r.bytes || 0;
  4652. state.mangleLastPackets = r.packets || 0;
  4653. state.mangleLastTimestamp = Date.now();
  4654. state.mangleStatRateHistory = new Array(30).fill(0);
  4655. state.mangleStatPktHistory = new Array(30).fill(0);
  4656. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4657. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4658. toggleMangleActionFields();
  4659. document.getElementById('mangle-modal').classList.remove('hidden');
  4660. }
  4661. function closeMangleModal() {
  4662. stopMangleStatPolling();
  4663. document.getElementById('mangle-modal').classList.add('hidden');
  4664. }
  4665. function copyMangleRule() {
  4666. document.getElementById('mangle-modal-id').value = '';
  4667. const badge = document.getElementById('mangle-modal-badge');
  4668. if (badge) badge.innerText = 'New...';
  4669. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4670. }
  4671. function resetCurrentMangleRuleCounters() {
  4672. state.mangleStatRateHistory = new Array(30).fill(0);
  4673. state.mangleStatPktHistory = new Array(30).fill(0);
  4674. state.mangleLastBytes = 0;
  4675. state.mangleLastPackets = 0;
  4676. state.mangleLastTimestamp = Date.now();
  4677. const bEl = document.getElementById('mangle-stat-bytes');
  4678. const pEl = document.getElementById('mangle-stat-packets');
  4679. const rEl = document.getElementById('mangle-stat-rate');
  4680. const prEl = document.getElementById('mangle-stat-pktrate');
  4681. if (bEl) bEl.value = '0 B';
  4682. if (pEl) pEl.value = '0';
  4683. if (rEl) rEl.value = '0 bps';
  4684. if (prEl) prEl.value = '0 p/s';
  4685. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4686. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4687. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4688. }
  4689. async function applyMangleRule(closeAfter = false) {
  4690. const id = document.getElementById('mangle-modal-id').value;
  4691. const chain = document.getElementById('mangle-modal-chain').value;
  4692. const action = document.getElementById('mangle-modal-action').value;
  4693. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4694. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4695. const src = getMangleFieldVal('src', true);
  4696. const dst = getMangleFieldVal('dst', true);
  4697. const srclist = getMangleFieldVal('srclist', true);
  4698. const dstlist = getMangleFieldVal('dstlist', true);
  4699. const srcgeo = getMangleFieldVal('srcgeo', true);
  4700. const dstgeo = getMangleFieldVal('dstgeo', true);
  4701. const proto = getMangleFieldVal('proto', true);
  4702. const sport = getMangleFieldVal('sport', true);
  4703. const dport = getMangleFieldVal('dport', true);
  4704. const anyport = getMangleFieldVal('anyport', true);
  4705. const iniface = getMangleFieldVal('iniface', true);
  4706. const outiface = getMangleFieldVal('outiface', true);
  4707. const inifacelist = getMangleFieldVal('inifacelist', true);
  4708. const outifacelist = getMangleFieldVal('outifacelist', true);
  4709. const pktmark = getMangleFieldVal('pktmark', true);
  4710. const connmark = getMangleFieldVal('connmark', true);
  4711. const routingmark = getMangleFieldVal('routingmark', true);
  4712. const conntype = getMangleFieldVal('conntype', false);
  4713. const states = [];
  4714. const csBox = document.getElementById('mangle-field-cs');
  4715. if (csBox && !csBox.classList.contains('hidden')) {
  4716. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4717. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4718. });
  4719. }
  4720. const natStates = [];
  4721. const natBox = document.getElementById('mangle-field-natstate');
  4722. if (natBox && !natBox.classList.contains('hidden')) {
  4723. ['srcnat', 'dstnat'].forEach(s => {
  4724. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4725. });
  4726. }
  4727. const payload = {
  4728. id,
  4729. chain,
  4730. action,
  4731. protocol: proto || 'all',
  4732. src_address: src,
  4733. dst_address: dst,
  4734. src_port: sport,
  4735. dst_port: dport,
  4736. any_port: anyport,
  4737. in_interface: iniface,
  4738. out_interface: outiface,
  4739. in_interface_list: inifacelist,
  4740. out_interface_list: outifacelist,
  4741. packet_mark: pktmark,
  4742. connection_mark: connmark,
  4743. routing_mark: routingmark,
  4744. connection_type: conntype,
  4745. connection_state: states,
  4746. connection_nat_state: natStates,
  4747. src_address_list: srclist,
  4748. dst_address_list: dstlist,
  4749. src_geoip: srcgeo,
  4750. dst_geoip: dstgeo,
  4751. comment,
  4752. disabled: !enabled,
  4753. // Advanced tab
  4754. layer7_protocol: getMangleFieldVal('layer7', false),
  4755. content: getMangleFieldVal('content', false),
  4756. connection_bytes: getMangleFieldVal('connbytes', false),
  4757. connection_rate: getMangleFieldVal('connrate', false),
  4758. pcc: getMangleFieldVal('pcc', false),
  4759. src_mac_address: getMangleFieldVal('srcmac', true),
  4760. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4761. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4762. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4763. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4764. ipsec_policy: getMangleFieldVal('ipsec', false),
  4765. tls_host: getMangleFieldVal('tlshost', false),
  4766. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4767. priority: getMangleFieldVal('priority', false),
  4768. dscp: getMangleFieldVal('dscp', false),
  4769. tcp_mss: getMangleFieldVal('tcpmss', false),
  4770. tos: document.getElementById('mangle-val-tos')?.value || '',
  4771. packet_size: getMangleFieldVal('pktsize', false),
  4772. random: getMangleFieldVal('random', false),
  4773. tcp_flags: getMangleFieldVal('tcpflags', false),
  4774. icmp_options: getMangleFieldVal('icmpoptions', false),
  4775. ipv4_options: getMangleFieldVal('ipv4options', false),
  4776. ttl: getMangleFieldVal('ttl', false),
  4777. // Extra tab
  4778. nth: getMangleFieldVal('nth', false),
  4779. connection_limit: getMangleFieldVal('connlimit', false),
  4780. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4781. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4782. hotspot: getMangleFieldVal('hotspot', false),
  4783. ip_fragment: getMangleFieldVal('ipfragment', false),
  4784. limit: getMangleFieldVal('limit', false),
  4785. dst_limit: getMangleFieldVal('dstlimit', false),
  4786. time: getMangleFieldVal('time', false),
  4787. psd: getMangleFieldVal('psd', false),
  4788. // Action tab
  4789. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4790. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4791. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4792. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4793. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4794. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4795. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4796. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4797. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4798. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4799. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4800. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4801. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4802. log: document.getElementById('mangle-modal-log')?.checked || false,
  4803. log_prefix: getMangleFieldVal('logprefix', false)
  4804. };
  4805. try {
  4806. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4807. method: 'POST',
  4808. headers: { 'Content-Type': 'application/json' },
  4809. body: JSON.stringify(payload)
  4810. });
  4811. if (res.ok) {
  4812. const data = await res.json();
  4813. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4814. loadFirewall(false);
  4815. if (closeAfter) {
  4816. closeMangleModal();
  4817. } else {
  4818. if (data.id) {
  4819. document.getElementById('mangle-modal-id').value = data.id;
  4820. const badge = document.getElementById('mangle-modal-badge');
  4821. if (badge) badge.innerText = `#${data.id}`;
  4822. }
  4823. }
  4824. } else {
  4825. const err = await res.json();
  4826. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4827. }
  4828. } catch (err) {
  4829. showToast('Error', err.message, 'error');
  4830. }
  4831. }
  4832. function submitSaveMangleRule(e) {
  4833. if (e && e.preventDefault) e.preventDefault();
  4834. return applyMangleRule(true);
  4835. }
  4836. function startMangleStatPolling() {
  4837. stopMangleStatPolling();
  4838. pollMangleRuleStats();
  4839. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4840. }
  4841. function stopMangleStatPolling() {
  4842. if (state.mangleStatInterval) {
  4843. clearInterval(state.mangleStatInterval);
  4844. state.mangleStatInterval = null;
  4845. }
  4846. }
  4847. async function pollMangleRuleStats() {
  4848. const id = document.getElementById('mangle-modal-id')?.value;
  4849. if (!id) {
  4850. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4851. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4852. return;
  4853. }
  4854. try {
  4855. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4856. if (!res.ok) return;
  4857. const rules = await res.json();
  4858. const r = rules.find(x => x.id === id);
  4859. if (!r) return;
  4860. const now = Date.now();
  4861. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4862. state.mangleLastTimestamp = now;
  4863. const curBytes = r.bytes || 0;
  4864. const curPackets = r.packets || 0;
  4865. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4866. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4867. state.mangleLastBytes = curBytes;
  4868. state.mangleLastPackets = curPackets;
  4869. const rateBps = Math.round((deltaBytes * 8) / dt);
  4870. const ratePkt = Math.round(deltaPkts / dt);
  4871. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4872. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4873. state.mangleStatRateHistory.push(rateBps);
  4874. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4875. state.mangleStatPktHistory.push(ratePkt);
  4876. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4877. const bEl = document.getElementById('mangle-stat-bytes');
  4878. const pEl = document.getElementById('mangle-stat-packets');
  4879. const rEl = document.getElementById('mangle-stat-rate');
  4880. const prEl = document.getElementById('mangle-stat-pktrate');
  4881. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4882. if (pEl) pEl.value = curPackets.toLocaleString();
  4883. if (rEl) rEl.value = formatBps(rateBps);
  4884. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4885. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4886. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4887. } catch (e) {
  4888. console.error('Error polling Mangle rule stats', e);
  4889. }
  4890. }
  4891. async function moveMangleRule(id, dir) {
  4892. try {
  4893. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4894. method: 'POST',
  4895. headers: { 'Content-Type': 'application/json' },
  4896. body: JSON.stringify({ direction: dir })
  4897. });
  4898. if (res.ok) loadFirewall(false);
  4899. } catch (err) {
  4900. showToast('Error', err.message, 'error');
  4901. }
  4902. }
  4903. async function toggleMangleRuleState(id, disabled) {
  4904. try {
  4905. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4906. method: 'POST',
  4907. headers: { 'Content-Type': 'application/json' },
  4908. body: JSON.stringify({ disabled })
  4909. });
  4910. if (res.ok) loadFirewall(false);
  4911. } catch (err) {
  4912. showToast('Error', err.message, 'error');
  4913. }
  4914. }
  4915. async function deleteMangleRule(id) {
  4916. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4917. try {
  4918. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4919. if (res.ok) {
  4920. showToast('Deleted', 'Mangle rule removed', 'success');
  4921. loadFirewall(false);
  4922. }
  4923. } catch (err) {
  4924. showToast('Error', err.message, 'error');
  4925. }
  4926. }
  4927. // ----------------- Address Lists -----------------
  4928. function renderAddressLists() {
  4929. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4930. const tbody = document.getElementById('addrlist-table-body');
  4931. const empty = document.getElementById('addrlist-empty');
  4932. if (!tbody) return;
  4933. tbody.innerHTML = '';
  4934. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4935. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4936. // Update filter select
  4937. const sel = document.getElementById('addrlist-filter-name');
  4938. if (sel) {
  4939. const cur = sel.value;
  4940. sel.innerHTML = '<option value="">All Lists</option>';
  4941. const set = new Set((state.addressLists || []).map(a => a.name));
  4942. set.forEach(n => {
  4943. const opt = document.createElement('option');
  4944. opt.value = n;
  4945. opt.innerText = n;
  4946. if (n === cur) opt.selected = true;
  4947. sel.appendChild(opt);
  4948. });
  4949. }
  4950. if (entries.length === 0) {
  4951. empty?.classList.remove('hidden');
  4952. return;
  4953. }
  4954. empty?.classList.add('hidden');
  4955. entries.forEach((e, idx) => {
  4956. const tr = document.createElement('tr');
  4957. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4958. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4959. tr.innerHTML = `
  4960. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4961. <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>
  4962. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4963. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4964. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4965. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4966. <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>
  4967. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4968. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4969. </td>
  4970. `;
  4971. tbody.appendChild(tr);
  4972. });
  4973. populateCommonAddrListDatalist();
  4974. }
  4975. function openAddAddrListModal() {
  4976. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4977. document.getElementById('addrlist-modal-id').value = '';
  4978. document.getElementById('addrlist-modal-name').value = '';
  4979. document.getElementById('addrlist-modal-addr').value = '';
  4980. document.getElementById('addrlist-modal-comment').value = '';
  4981. document.getElementById('addrlist-modal-disabled').checked = false;
  4982. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4983. if (submitBtn) submitBtn.innerText = 'Add to List';
  4984. document.getElementById('addrlist-modal').classList.remove('hidden');
  4985. }
  4986. function openEditAddrListModal(id) {
  4987. const e = (state.addressLists || []).find(item => item.id === id);
  4988. if (!e) return;
  4989. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4990. document.getElementById('addrlist-modal-id').value = e.id;
  4991. document.getElementById('addrlist-modal-name').value = e.name;
  4992. document.getElementById('addrlist-modal-addr').value = e.address;
  4993. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4994. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4995. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4996. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4997. document.getElementById('addrlist-modal').classList.remove('hidden');
  4998. }
  4999. function closeAddrListModal() {
  5000. document.getElementById('addrlist-modal').classList.add('hidden');
  5001. }
  5002. async function submitSaveAddrList(e) {
  5003. e.preventDefault();
  5004. const id = document.getElementById('addrlist-modal-id').value;
  5005. const name = document.getElementById('addrlist-modal-name').value.trim();
  5006. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5007. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5008. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5009. try {
  5010. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5011. method: 'POST',
  5012. headers: { 'Content-Type': 'application/json' },
  5013. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5014. });
  5015. if (res.ok) {
  5016. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5017. closeAddrListModal();
  5018. loadFirewall(false);
  5019. } else {
  5020. const err = await res.json();
  5021. showToast('Error', err.message || 'Failed to save address list', 'error');
  5022. }
  5023. } catch (err) {
  5024. showToast('Error', err.message, 'error');
  5025. }
  5026. }
  5027. async function toggleAddrListState(id, disabled) {
  5028. try {
  5029. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5030. method: 'POST',
  5031. headers: { 'Content-Type': 'application/json' },
  5032. body: JSON.stringify({ disabled })
  5033. });
  5034. if (res.ok) {
  5035. loadFirewall(false);
  5036. }
  5037. } catch (err) {
  5038. showToast('Error', err.message, 'error');
  5039. }
  5040. }
  5041. async function deleteAddrList(id) {
  5042. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5043. try {
  5044. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5045. if (res.ok) {
  5046. showToast('Deleted', 'Address list item removed', 'info');
  5047. loadFirewall(false);
  5048. }
  5049. } catch (err) {
  5050. showToast('Error', err.message, 'error');
  5051. }
  5052. }
  5053. // ----------------- Geo-Location IP Management -----------------
  5054. async function loadGeoIP() {
  5055. try {
  5056. const [statusRes, countriesRes] = await Promise.all([
  5057. fetch(`${API_BASE}/firewall/geoip/status`),
  5058. fetch(`${API_BASE}/firewall/geoip/countries`)
  5059. ]);
  5060. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5061. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5062. updateGeoHeader();
  5063. renderGeoCountries();
  5064. } catch (err) {
  5065. console.error('Failed to load GeoIP:', err);
  5066. }
  5067. }
  5068. function getGeoUsageMap() {
  5069. const usage = {};
  5070. const checkRule = (r, type) => {
  5071. ['src_geoip', 'dst_geoip'].forEach(field => {
  5072. let val = (r && r[field]) || '';
  5073. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5074. if (code) {
  5075. if (!usage[code]) usage[code] = [];
  5076. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5077. if (!usage[code].includes(label)) usage[code].push(label);
  5078. }
  5079. });
  5080. };
  5081. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5082. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5083. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5084. return usage;
  5085. }
  5086. function updateGeoHeader() {
  5087. const s = state.geoStatus || {};
  5088. const statusBadge = document.getElementById('geo-status-badge');
  5089. if (statusBadge) {
  5090. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5091. statusBadge.className = s.auto_update
  5092. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5093. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5094. }
  5095. const intervalLabel = document.getElementById('geo-interval-label');
  5096. if (intervalLabel) {
  5097. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5098. }
  5099. const usageMap = getGeoUsageMap();
  5100. const inUseCount = Object.keys(usageMap).length;
  5101. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5102. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5103. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5104. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5105. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5106. if (lastSyncEl) {
  5107. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5108. const d = new Date(s.last_updated);
  5109. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5110. } else {
  5111. lastSyncEl.innerText = 'Never (Sync Pending)';
  5112. }
  5113. }
  5114. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5115. if (nextSyncEl) {
  5116. if (s.next_update && !s.next_update.startsWith('0001')) {
  5117. const d = new Date(s.next_update);
  5118. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5119. } else {
  5120. nextSyncEl.innerText = '-';
  5121. }
  5122. }
  5123. const badge = document.getElementById('fw-badge-geo');
  5124. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5125. }
  5126. function renderGeoCountries() {
  5127. const tbody = document.getElementById('geo-table-body');
  5128. const empty = document.getElementById('geo-empty');
  5129. if (!tbody) return;
  5130. tbody.innerHTML = '';
  5131. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5132. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5133. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5134. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5135. const usageMap = getGeoUsageMap();
  5136. const countries = (state.geoCountries || []).filter(c => {
  5137. const isUsed = !!usageMap[c.code];
  5138. if (inUseOnly && !isUsed) return false;
  5139. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5140. if (continent && c.continent !== continent) return false;
  5141. if (q) {
  5142. const matchCode = c.code.toLowerCase().includes(q);
  5143. const matchName = c.name.toLowerCase().includes(q);
  5144. if (!matchCode && !matchName) return false;
  5145. }
  5146. return true;
  5147. });
  5148. if (countries.length === 0) {
  5149. empty?.classList.remove('hidden');
  5150. return;
  5151. }
  5152. empty?.classList.add('hidden');
  5153. countries.forEach(c => {
  5154. const tr = document.createElement('tr');
  5155. const isUsed = !!usageMap[c.code];
  5156. const rulesUsing = usageMap[c.code] || [];
  5157. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5158. let statusHtml = '';
  5159. if (isUsed) {
  5160. 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>`;
  5161. } else if (c.subnet_count > 0) {
  5162. 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>';
  5163. } else {
  5164. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5165. }
  5166. tr.innerHTML = `
  5167. <td class="py-2.5 px-3 text-center">
  5168. <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'}">
  5169. ${c.code}
  5170. </span>
  5171. </td>
  5172. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5173. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5174. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5175. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5176. </td>
  5177. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5178. <td class="py-2.5 px-3">
  5179. ${statusHtml}
  5180. </td>
  5181. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5182. <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>
  5183. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5184. </td>
  5185. `;
  5186. tbody.appendChild(tr);
  5187. });
  5188. }
  5189. function quickFilterGeo(preset) {
  5190. const searchInput = document.getElementById('geo-search-input');
  5191. const continentSel = document.getElementById('geo-continent-filter');
  5192. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5193. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5194. if (searchInput) searchInput.value = '';
  5195. if (continentSel) continentSel.value = '';
  5196. if (inUseCheck) inUseCheck.checked = false;
  5197. if (cachedCheck) cachedCheck.checked = false;
  5198. if (preset === 'GR') {
  5199. if (searchInput) searchInput.value = 'Greece';
  5200. } else if (preset === 'Europe') {
  5201. if (continentSel) continentSel.value = 'Europe';
  5202. } else if (preset === 'HIGHRISK') {
  5203. if (searchInput) searchInput.value = 'China';
  5204. }
  5205. renderGeoCountries();
  5206. }
  5207. async function toggleGeoCountry(code, enabled) {
  5208. try {
  5209. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5210. method: 'POST',
  5211. headers: { 'Content-Type': 'application/json' },
  5212. body: JSON.stringify({ enabled })
  5213. });
  5214. if (res.ok) {
  5215. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5216. loadGeoIP();
  5217. } else {
  5218. const err = await res.json();
  5219. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5220. }
  5221. } catch (err) {
  5222. showToast('Error', err.message, 'error');
  5223. }
  5224. }
  5225. async function updateGeoCountry(code) {
  5226. try {
  5227. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5228. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5229. if (res.ok) {
  5230. const data = await res.json();
  5231. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5232. loadGeoIP();
  5233. } else {
  5234. const err = await res.json();
  5235. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5236. }
  5237. } catch (err) {
  5238. showToast('Error', err.message, 'error');
  5239. }
  5240. }
  5241. async function triggerGeoUpdateNow() {
  5242. const spinner = document.getElementById('geo-update-spinner');
  5243. if (spinner) spinner.classList.remove('hidden');
  5244. try {
  5245. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5246. if (res.ok) {
  5247. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5248. setTimeout(() => {
  5249. loadGeoIP();
  5250. if (spinner) spinner.classList.add('hidden');
  5251. }, 2500);
  5252. } else {
  5253. const err = await res.json();
  5254. showToast('Notice', err.message || 'Update in progress', 'info');
  5255. if (spinner) spinner.classList.add('hidden');
  5256. }
  5257. } catch (err) {
  5258. showToast('Error', err.message, 'error');
  5259. if (spinner) spinner.classList.add('hidden');
  5260. }
  5261. }
  5262. async function applyGeoPreset(preset) {
  5263. try {
  5264. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5265. method: 'POST',
  5266. headers: { 'Content-Type': 'application/json' },
  5267. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5268. });
  5269. if (res.ok) {
  5270. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5271. loadGeoIP();
  5272. }
  5273. } catch (err) {
  5274. showToast('Error', err.message, 'error');
  5275. }
  5276. }
  5277. function openGeoIntervalModal() {
  5278. const s = state.geoStatus || {};
  5279. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5280. const sel = document.getElementById('geo-cfg-interval');
  5281. const customBox = document.getElementById('geo-cfg-custom-box');
  5282. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5283. const curHours = s.interval_hours || 24;
  5284. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5285. if (matchOption) {
  5286. sel.value = String(curHours);
  5287. customBox.classList.add('hidden');
  5288. } else {
  5289. sel.value = 'custom';
  5290. customHoursInput.value = curHours;
  5291. customBox.classList.remove('hidden');
  5292. }
  5293. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5294. }
  5295. function closeGeoIntervalModal() {
  5296. document.getElementById('geo-interval-modal').classList.add('hidden');
  5297. }
  5298. function toggleCustomGeoInterval() {
  5299. const val = document.getElementById('geo-cfg-interval').value;
  5300. const customBox = document.getElementById('geo-cfg-custom-box');
  5301. if (val === 'custom') {
  5302. customBox.classList.remove('hidden');
  5303. } else {
  5304. customBox.classList.add('hidden');
  5305. }
  5306. }
  5307. async function submitGeoIntervalSettings(e) {
  5308. e.preventDefault();
  5309. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5310. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5311. let hours = 24;
  5312. if (intervalVal === 'custom') {
  5313. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5314. } else {
  5315. hours = parseInt(intervalVal, 10) || 24;
  5316. }
  5317. try {
  5318. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5319. method: 'POST',
  5320. headers: { 'Content-Type': 'application/json' },
  5321. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5322. });
  5323. if (res.ok) {
  5324. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5325. closeGeoIntervalModal();
  5326. loadGeoIP();
  5327. } else {
  5328. const err = await res.json();
  5329. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5330. }
  5331. } catch (err) {
  5332. showToast('Error', err.message, 'error');
  5333. }
  5334. }
  5335. async function viewGeoSubnets(code, name) {
  5336. if (!name) {
  5337. const found = (state.geoCountries || []).find(x => x.code === code);
  5338. name = found ? found.name : code;
  5339. }
  5340. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5341. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5342. const listEl = document.getElementById('geo-subnets-list');
  5343. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5344. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5345. try {
  5346. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5347. if (res.ok) {
  5348. const data = await res.json();
  5349. const subnets = data.subnets || [];
  5350. if (subnets.length === 0) {
  5351. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5352. } else {
  5353. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5354. }
  5355. } else {
  5356. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5357. }
  5358. } catch (err) {
  5359. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5360. }
  5361. }
  5362. function closeGeoSubnetsModal() {
  5363. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5364. }
  5365. // ----------------- Active Connections Tracking -----------------
  5366. async function loadConnections() {
  5367. try {
  5368. const res = await fetch(`${API_BASE}/firewall/connections`);
  5369. const data = await res.json();
  5370. state.connections = Array.isArray(data) ? data : [];
  5371. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5372. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5373. renderConnections();
  5374. } catch (err) {
  5375. console.error('Failed to load connections:', err);
  5376. }
  5377. }
  5378. function renderConnections() {
  5379. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5380. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5381. const tbody = document.getElementById('conns-table-body');
  5382. const empty = document.getElementById('conns-empty');
  5383. if (!tbody) return;
  5384. tbody.innerHTML = '';
  5385. const conns = (state.connections || []).filter(c => {
  5386. if (protoFilter && c.protocol !== protoFilter) return false;
  5387. if (search) {
  5388. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5389. if (!line.includes(search)) return false;
  5390. }
  5391. return true;
  5392. });
  5393. if (conns.length === 0) {
  5394. empty?.classList.remove('hidden');
  5395. return;
  5396. }
  5397. empty?.classList.add('hidden');
  5398. conns.slice(0, 150).forEach(c => {
  5399. const tr = document.createElement('tr');
  5400. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5401. let stateColor = 'text-slate-400';
  5402. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5403. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5404. tr.innerHTML = `
  5405. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5406. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5407. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5408. <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>
  5409. <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>
  5410. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5411. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5412. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5413. <td class="py-2.5 px-3 text-right font-sans">
  5414. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  5415. </td>
  5416. `;
  5417. tbody.appendChild(tr);
  5418. });
  5419. }
  5420. async function killConnection(protocol, src, sport, dst, dport) {
  5421. try {
  5422. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5423. method: 'POST',
  5424. headers: { 'Content-Type': 'application/json' },
  5425. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5426. });
  5427. if (res.ok) {
  5428. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5429. loadConnections();
  5430. }
  5431. } catch (err) {
  5432. showToast('Error', err.message, 'error');
  5433. }
  5434. }
  5435. async function resetFirewallCounters() {
  5436. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5437. try {
  5438. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5439. if (res.ok) {
  5440. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5441. loadFirewall(false);
  5442. }
  5443. } catch (err) {
  5444. showToast('Error', err.message, 'error');
  5445. }
  5446. }
  5447. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5448. function switchRoutesSubTab(tab) {
  5449. state.routesSubTab = tab;
  5450. const tabs = ['routes', 'rules', 'tables'];
  5451. tabs.forEach(t => {
  5452. const panel = document.getElementById(`routes-subtab-${t}`);
  5453. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5454. if (panel) {
  5455. if (t === tab) panel.classList.remove('hidden');
  5456. else panel.classList.add('hidden');
  5457. }
  5458. if (btn) {
  5459. if (t === tab) {
  5460. 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';
  5461. } else {
  5462. 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';
  5463. }
  5464. }
  5465. });
  5466. setTimeout(initTableSorting, 50);
  5467. }
  5468. async function loadRoutes() {
  5469. try {
  5470. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5471. fetch(`${API_BASE}/routes`),
  5472. fetch(`${API_BASE}/routing/rules`),
  5473. fetch(`${API_BASE}/routing/tables`)
  5474. ]);
  5475. if (routesRes.ok) state.routes = await routesRes.json();
  5476. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5477. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5478. const bRoutes = document.getElementById('routes-badge-routes');
  5479. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5480. const showSystem = document.getElementById('prule-show-system')?.checked;
  5481. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5482. const bRules = document.getElementById('routes-badge-rules');
  5483. if (bRules) bRules.innerText = userRules.length;
  5484. const bTables = document.getElementById('routes-badge-tables');
  5485. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5486. const bRoutesCount = document.getElementById('badge-routes-count');
  5487. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5488. renderRoutesList();
  5489. renderPolicyRules();
  5490. renderRoutingTables();
  5491. } catch (err) {
  5492. console.error('Failed to load routing:', err);
  5493. }
  5494. }
  5495. function renderRoutesList() {
  5496. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5497. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5498. const tbody = document.getElementById('routes-table-body');
  5499. const empty = document.getElementById('routes-empty');
  5500. if (!tbody) return;
  5501. tbody.innerHTML = '';
  5502. // Update table filter select
  5503. const sel = document.getElementById('routes-filter-table');
  5504. if (sel) {
  5505. const cur = sel.value;
  5506. sel.innerHTML = '<option value="">All Tables</option>';
  5507. (state.routingTables || []).forEach(t => {
  5508. const opt = document.createElement('option');
  5509. opt.value = t.name;
  5510. opt.innerText = t.name;
  5511. if (t.name === cur) opt.selected = true;
  5512. sel.appendChild(opt);
  5513. });
  5514. }
  5515. const routes = (state.routes || []).filter(r => {
  5516. if (tableFilter && r.routing_table !== tableFilter) return false;
  5517. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5518. if (typeFilter === 'multicast' && !r.multicast) return false;
  5519. if (typeFilter === 'static' && !r.static) return false;
  5520. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5521. if (typeFilter === 'connected' && !r.connect) return false;
  5522. return true;
  5523. });
  5524. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5525. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5526. let summaryText = `${routes.length} Routes`;
  5527. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5528. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5529. const badgeEl = document.getElementById('routes-count-badge');
  5530. if (badgeEl) badgeEl.innerText = summaryText;
  5531. if (routes.length === 0) {
  5532. empty?.classList.remove('hidden');
  5533. return;
  5534. }
  5535. empty?.classList.add('hidden');
  5536. routes.forEach(r => {
  5537. const tr = document.createElement('tr');
  5538. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5539. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5540. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5541. let flags = '';
  5542. if (r.dynamic) flags += 'D';
  5543. if (r.active) flags += 'A';
  5544. if (r.connect) flags += 'C';
  5545. if (r.static) flags += 'S';
  5546. if (r.ecmp) flags += 'E';
  5547. if (r.multicast) flags += 'M';
  5548. if (r.disabled) flags += 'X';
  5549. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5550. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5551. if (r.check_gateway === 'internet') {
  5552. if (r.health_status === 'online') {
  5553. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5554. healthCell = `
  5555. <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)">
  5556. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5557. <span>Internet OK (${ms}ms)</span>
  5558. </span>
  5559. `;
  5560. } else if (r.health_status === 'offline') {
  5561. healthCell = `
  5562. <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.">
  5563. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5564. <span>Internet Down</span>
  5565. </span>
  5566. `;
  5567. } else {
  5568. healthCell = `
  5569. <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">
  5570. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  5571. <span>Checking...</span>
  5572. </span>
  5573. `;
  5574. }
  5575. } else if (r.check_gateway === 'ping') {
  5576. if (r.health_status === 'online') {
  5577. healthCell = `
  5578. <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">
  5579. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  5580. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  5581. </span>
  5582. `;
  5583. } else if (r.health_status === 'offline') {
  5584. healthCell = `
  5585. <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">
  5586. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5587. <span>Gateway Dead</span>
  5588. </span>
  5589. `;
  5590. }
  5591. }
  5592. const flagDescriptions = [];
  5593. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  5594. if (r.active) flagDescriptions.push('Active (A)');
  5595. if (r.connect) flagDescriptions.push('Connected (C)');
  5596. if (r.static) flagDescriptions.push('Static (S)');
  5597. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  5598. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  5599. if (r.disabled) flagDescriptions.push('Disabled (X)');
  5600. tr.innerHTML = `
  5601. <td class="py-2.5 px-3 text-center">
  5602. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  5603. 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')
  5604. }" title="Flags: ${flagDescriptions.join(', ')}">
  5605. ${flags || '-'}
  5606. </span>
  5607. </td>
  5608. <td class="py-2.5 px-3">
  5609. <div class="flex items-center gap-1.5 flex-wrap">
  5610. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  5611. ${r.ecmp ? `
  5612. <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)">
  5613. <span>⚡ ECMP</span>
  5614. </span>
  5615. ` : ''}
  5616. ${r.multicast ? `
  5617. <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">
  5618. <span>IGMP</span>
  5619. </span>
  5620. ` : ''}
  5621. </div>
  5622. </td>
  5623. <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>
  5624. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5625. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5626. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5627. <td class="py-2.5 px-3">${healthCell}</td>
  5628. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5629. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5630. ${r.static ? `
  5631. <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>
  5632. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5633. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5634. ` : `
  5635. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5636. `}
  5637. </td>
  5638. `;
  5639. tbody.appendChild(tr);
  5640. });
  5641. }
  5642. function openAddRouteModal() {
  5643. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5644. document.getElementById('route-modal-id').value = '';
  5645. document.getElementById('route-modal-old-dst').value = '';
  5646. document.getElementById('route-modal-old-gw').value = '';
  5647. document.getElementById('route-modal-old-distance').value = '';
  5648. document.getElementById('route-modal-old-table').value = '';
  5649. document.getElementById('route-modal-old-iface').value = '';
  5650. const dstInput = document.getElementById('route-modal-dst');
  5651. const gwInput = document.getElementById('route-modal-gw');
  5652. const distInput = document.getElementById('route-modal-distance');
  5653. const ifaceSelect = document.getElementById('route-modal-iface');
  5654. const tableSelect = document.getElementById('route-modal-table');
  5655. const commentInput = document.getElementById('route-modal-comment');
  5656. const disCheck = document.getElementById('route-modal-disabled');
  5657. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5658. dstInput.disabled = false;
  5659. dstInput.value = '0.0.0.0/0';
  5660. gwInput.disabled = false;
  5661. gwInput.value = '';
  5662. distInput.disabled = false;
  5663. distInput.value = '1';
  5664. ifaceSelect.disabled = false;
  5665. tableSelect.disabled = false;
  5666. commentInput.disabled = false;
  5667. commentInput.value = '';
  5668. disCheck.disabled = false;
  5669. disCheck.checked = false;
  5670. if (saveBtn) saveBtn.classList.remove('hidden');
  5671. const checkGw = document.getElementById('route-modal-check-gw');
  5672. if (checkGw) checkGw.value = 'internet';
  5673. const checkTarget = document.getElementById('route-modal-check-target');
  5674. if (checkTarget) checkTarget.value = '1.1.1.1';
  5675. const checkInterval = document.getElementById('route-modal-check-interval');
  5676. if (checkInterval) checkInterval.value = '5';
  5677. const checkThresh = document.getElementById('route-modal-check-threshold');
  5678. if (checkThresh) checkThresh.value = '3';
  5679. toggleRouteCheckModeUI();
  5680. populateInterfaceSelect('route-modal-iface');
  5681. // Populate tables
  5682. tableSelect.innerHTML = '';
  5683. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5684. const opt = document.createElement('option');
  5685. opt.value = t.name;
  5686. opt.innerText = t.name;
  5687. if (t.name === 'main') opt.selected = true;
  5688. tableSelect.appendChild(opt);
  5689. });
  5690. document.getElementById('route-modal').classList.remove('hidden');
  5691. }
  5692. function openEditRouteModal(id) {
  5693. const r = (state.routes || []).find(route => route.id === id);
  5694. if (!r) return;
  5695. const isStatic = !!r.static;
  5696. document.getElementById('route-modal-title').innerText = isStatic
  5697. ? `Edit Route: ${r.dst_address}`
  5698. : `Route Properties (Read Only): ${r.dst_address}`;
  5699. document.getElementById('route-modal-id').value = r.id;
  5700. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5701. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5702. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5703. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5704. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5705. const dstInput = document.getElementById('route-modal-dst');
  5706. const gwInput = document.getElementById('route-modal-gw');
  5707. const distInput = document.getElementById('route-modal-distance');
  5708. const ifaceSelect = document.getElementById('route-modal-iface');
  5709. const tableSelect = document.getElementById('route-modal-table');
  5710. const commentInput = document.getElementById('route-modal-comment');
  5711. const disCheck = document.getElementById('route-modal-disabled');
  5712. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5713. dstInput.value = r.dst_address;
  5714. gwInput.value = r.gateway || '';
  5715. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5716. commentInput.value = r.comment || '';
  5717. disCheck.checked = !!r.disabled;
  5718. const checkGw = document.getElementById('route-modal-check-gw');
  5719. if (checkGw) checkGw.value = r.check_gateway || 'none';
  5720. const checkTarget = document.getElementById('route-modal-check-target');
  5721. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  5722. const checkInterval = document.getElementById('route-modal-check-interval');
  5723. if (checkInterval) checkInterval.value = r.check_interval || 5;
  5724. const checkThresh = document.getElementById('route-modal-check-threshold');
  5725. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  5726. toggleRouteCheckModeUI();
  5727. dstInput.disabled = !isStatic;
  5728. gwInput.disabled = !isStatic;
  5729. distInput.disabled = !isStatic;
  5730. ifaceSelect.disabled = !isStatic;
  5731. tableSelect.disabled = !isStatic;
  5732. commentInput.disabled = !isStatic;
  5733. disCheck.disabled = !isStatic;
  5734. if (checkGw) checkGw.disabled = !isStatic;
  5735. if (checkTarget) checkTarget.disabled = !isStatic;
  5736. if (checkInterval) checkInterval.disabled = !isStatic;
  5737. if (checkThresh) checkThresh.disabled = !isStatic;
  5738. if (saveBtn) {
  5739. if (isStatic) {
  5740. saveBtn.classList.remove('hidden');
  5741. } else {
  5742. saveBtn.classList.add('hidden');
  5743. }
  5744. }
  5745. populateInterfaceSelect('route-modal-iface', r.interface);
  5746. tableSelect.innerHTML = '';
  5747. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5748. const opt = document.createElement('option');
  5749. opt.value = t.name;
  5750. opt.innerText = t.name;
  5751. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5752. tableSelect.appendChild(opt);
  5753. });
  5754. document.getElementById('route-modal').classList.remove('hidden');
  5755. }
  5756. function closeRouteModal() {
  5757. document.getElementById('route-modal').classList.add('hidden');
  5758. }
  5759. function setRouteCheckTarget(ip) {
  5760. const inp = document.getElementById('route-modal-check-target');
  5761. if (inp) inp.value = ip;
  5762. }
  5763. function toggleRouteCheckModeUI() {
  5764. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  5765. const targetRow = document.getElementById('route-row-check-target');
  5766. const paramsRow = document.getElementById('route-row-check-params');
  5767. if (mode === 'none') {
  5768. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5769. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  5770. } else if (mode === 'ping') {
  5771. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5772. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5773. } else { // internet
  5774. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  5775. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5776. }
  5777. }
  5778. async function submitSaveRoute(e) {
  5779. e.preventDefault();
  5780. const id = document.getElementById('route-modal-id').value;
  5781. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5782. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5783. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5784. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5785. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5786. const dst = document.getElementById('route-modal-dst').value.trim();
  5787. const gw = document.getElementById('route-modal-gw').value.trim();
  5788. const table = document.getElementById('route-modal-table').value;
  5789. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5790. const iface = document.getElementById('route-modal-iface').value;
  5791. const comment = document.getElementById('route-modal-comment').value.trim();
  5792. const disabled = document.getElementById('route-modal-disabled').checked;
  5793. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  5794. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  5795. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  5796. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  5797. if (!dst) {
  5798. showToast('Error', 'Destination address is required', 'error');
  5799. return;
  5800. }
  5801. if (!gw && !iface) {
  5802. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5803. return;
  5804. }
  5805. const payload = {
  5806. id,
  5807. old_dst_address: oldDst,
  5808. old_gateway: oldGw,
  5809. old_routing_table: oldTable,
  5810. old_interface: oldIface,
  5811. dst_address: dst,
  5812. gateway: gw || iface,
  5813. routing_table: table,
  5814. distance,
  5815. interface: iface,
  5816. comment,
  5817. disabled,
  5818. check_gateway,
  5819. check_target,
  5820. check_interval,
  5821. check_threshold
  5822. };
  5823. if (oldDistStr !== undefined && oldDistStr !== '') {
  5824. payload.old_distance = parseInt(oldDistStr, 10);
  5825. }
  5826. try {
  5827. const res = await fetch(`${API_BASE}/routes`, {
  5828. method: 'POST',
  5829. headers: { 'Content-Type': 'application/json' },
  5830. body: JSON.stringify(payload)
  5831. });
  5832. if (res.ok) {
  5833. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5834. closeRouteModal();
  5835. loadRoutes();
  5836. } else {
  5837. const err = await res.json();
  5838. showToast('Error', err.message || 'Failed to save route', 'error');
  5839. }
  5840. } catch (err) {
  5841. showToast('Error', err.message, 'error');
  5842. }
  5843. }
  5844. async function toggleRouteState(id, disabled) {
  5845. try {
  5846. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5847. method: 'POST',
  5848. headers: { 'Content-Type': 'application/json' },
  5849. body: JSON.stringify({ disabled })
  5850. });
  5851. if (res.ok) loadRoutes();
  5852. } catch (err) {
  5853. showToast('Error', err.message, 'error');
  5854. }
  5855. }
  5856. async function deleteRoute(id) {
  5857. if (!confirm('Are you sure you want to delete this route?')) return;
  5858. try {
  5859. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5860. if (res.ok) {
  5861. showToast('Deleted', 'Route removed', 'success');
  5862. loadRoutes();
  5863. }
  5864. } catch (err) {
  5865. showToast('Error', err.message, 'error');
  5866. }
  5867. }
  5868. // ----------------- Policy Rules (/ip route rule) -----------------
  5869. function renderPolicyRules() {
  5870. const tbody = document.getElementById('rules-table-body');
  5871. const empty = document.getElementById('rules-empty');
  5872. if (!tbody) return;
  5873. tbody.innerHTML = '';
  5874. const showSystem = document.getElementById('prule-show-system')?.checked;
  5875. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5876. const countBadge = document.getElementById('rules-count-badge');
  5877. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5878. const bRules = document.getElementById('routes-badge-rules');
  5879. if (bRules) bRules.innerText = filtered.length;
  5880. if (filtered.length === 0) {
  5881. empty?.classList.remove('hidden');
  5882. return;
  5883. }
  5884. empty?.classList.add('hidden');
  5885. filtered.forEach(pr => {
  5886. const isSys = pr.is_default || pr.is_system;
  5887. const tr = document.createElement('tr');
  5888. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5889. tr.innerHTML = `
  5890. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5891. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5892. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5893. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5894. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5895. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5896. <td class="py-2.5 px-3 text-right font-sans">
  5897. ${!pr.is_default ? `
  5898. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5899. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5900. </td>
  5901. `;
  5902. tbody.appendChild(tr);
  5903. });
  5904. }
  5905. function openAddPolicyRuleModal() {
  5906. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5907. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5908. document.getElementById('prule-modal-mark').value = '';
  5909. document.getElementById('prule-modal-src').value = '';
  5910. document.getElementById('prule-modal-dst').value = '';
  5911. const sel = document.getElementById('prule-modal-table');
  5912. sel.innerHTML = '';
  5913. (state.routingTables || []).forEach(t => {
  5914. const opt = document.createElement('option');
  5915. opt.value = t.name;
  5916. opt.innerText = t.name;
  5917. sel.appendChild(opt);
  5918. });
  5919. document.getElementById('prule-modal').classList.remove('hidden');
  5920. }
  5921. function closePolicyRuleModal() {
  5922. document.getElementById('prule-modal').classList.add('hidden');
  5923. }
  5924. async function submitSavePolicyRule(e) {
  5925. e.preventDefault();
  5926. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5927. const mark = document.getElementById('prule-modal-mark').value.trim();
  5928. const src = document.getElementById('prule-modal-src').value.trim();
  5929. const dst = document.getElementById('prule-modal-dst').value.trim();
  5930. const table = document.getElementById('prule-modal-table').value;
  5931. const action = document.getElementById('prule-modal-action').value;
  5932. try {
  5933. const res = await fetch(`${API_BASE}/routing/rules`, {
  5934. method: 'POST',
  5935. headers: { 'Content-Type': 'application/json' },
  5936. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5937. });
  5938. if (res.ok) {
  5939. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5940. closePolicyRuleModal();
  5941. loadRoutes();
  5942. } else {
  5943. const err = await res.json();
  5944. showToast('Error', err.message, 'error');
  5945. }
  5946. } catch (err) {
  5947. showToast('Error', err.message, 'error');
  5948. }
  5949. }
  5950. async function deletePolicyRule(id) {
  5951. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5952. try {
  5953. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5954. if (res.ok) {
  5955. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5956. loadRoutes();
  5957. }
  5958. } catch (err) {
  5959. showToast('Error', err.message, 'error');
  5960. }
  5961. }
  5962. // ----------------- Routing Tables -----------------
  5963. function renderRoutingTables() {
  5964. const tbody = document.getElementById('tables-table-body');
  5965. if (!tbody) return;
  5966. tbody.innerHTML = '';
  5967. (state.routingTables || []).forEach(t => {
  5968. const tr = document.createElement('tr');
  5969. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5970. tr.innerHTML = `
  5971. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5972. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5973. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5974. `;
  5975. tbody.appendChild(tr);
  5976. });
  5977. }
  5978. function openAddTableModal() {
  5979. document.getElementById('table-modal-name').value = '';
  5980. document.getElementById('table-modal-id').value = '';
  5981. document.getElementById('table-modal-comment').value = '';
  5982. document.getElementById('table-modal').classList.remove('hidden');
  5983. }
  5984. function closeTableModal() {
  5985. document.getElementById('table-modal').classList.add('hidden');
  5986. }
  5987. async function submitSaveTable(e) {
  5988. e.preventDefault();
  5989. const name = document.getElementById('table-modal-name').value.trim();
  5990. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5991. const comment = document.getElementById('table-modal-comment').value.trim();
  5992. try {
  5993. const res = await fetch(`${API_BASE}/routing/tables`, {
  5994. method: 'POST',
  5995. headers: { 'Content-Type': 'application/json' },
  5996. body: JSON.stringify({ name, table_id: id, comment })
  5997. });
  5998. if (res.ok) {
  5999. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6000. closeTableModal();
  6001. loadRoutes();
  6002. } else {
  6003. const err = await res.json();
  6004. showToast('Error', err.message, 'error');
  6005. }
  6006. } catch (err) {
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. }
  6010. async function loadDebianConfig() {
  6011. const view = document.getElementById('debian-config-view');
  6012. view.innerText = 'Generating live configuration...';
  6013. try {
  6014. const res = await fetch(`${API_BASE}/debian/config`);
  6015. const data = await res.json();
  6016. view.innerText = data.content || '# Empty config';
  6017. } catch (err) {
  6018. view.innerText = 'Failed to generate Debian network config.';
  6019. }
  6020. }
  6021. async function saveDebianConfig() {
  6022. try {
  6023. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6024. const data = await res.json();
  6025. if (res.ok) {
  6026. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6027. loadDebianConfig();
  6028. }
  6029. } catch (err) {
  6030. showToast('Error', err.message, 'error');
  6031. }
  6032. }
  6033. function showToast(title, message, type = 'info') {
  6034. const container = document.getElementById('toast-container');
  6035. const toast = document.createElement('div');
  6036. const borderColors = {
  6037. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6038. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6039. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6040. };
  6041. 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}`;
  6042. toast.innerHTML = `
  6043. <div class="flex-1">
  6044. <div class="font-bold text-xs text-white">${title}</div>
  6045. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6046. </div>
  6047. `;
  6048. container.appendChild(toast);
  6049. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6050. setTimeout(() => {
  6051. toast.classList.add('opacity-0', 'translate-y-2');
  6052. setTimeout(() => toast.remove(), 300);
  6053. }, 4000);
  6054. }
  6055. function formatTraffic(bytesPerSec) {
  6056. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6057. const kb = bytesPerSec / 1024;
  6058. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6059. const mb = kb / 1024;
  6060. return `${mb.toFixed(2)} MB/s`;
  6061. }
  6062. function toggleSidebar() {
  6063. const sb = document.getElementById('sidebar');
  6064. sb.classList.toggle('-translate-x-full');
  6065. }
  6066. // ======================== EoIP (Ethernet over IP) ========================
  6067. async function loadEoIP(populate = true) {
  6068. try {
  6069. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6070. const data = await res.json();
  6071. state.eoipTunnels = Array.isArray(data) ? data : [];
  6072. const badge = document.getElementById('eoip-count-badge');
  6073. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6074. const sideBadge = document.getElementById('badge-eoip-count');
  6075. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6076. renderEoIPTunnels();
  6077. } catch (err) {
  6078. console.error('Failed to load EoIP:', err);
  6079. }
  6080. }
  6081. function renderEoIPTunnels() {
  6082. const tbody = document.getElementById('eoip-table-body');
  6083. const empty = document.getElementById('eoip-empty');
  6084. if (!tbody) return;
  6085. tbody.innerHTML = '';
  6086. const tunnels = state.eoipTunnels || [];
  6087. if (tunnels.length === 0) {
  6088. empty?.classList.remove('hidden');
  6089. return;
  6090. }
  6091. empty?.classList.add('hidden');
  6092. tunnels.forEach(t => {
  6093. const tr = document.createElement('tr');
  6094. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6095. tr.innerHTML = `
  6096. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6097. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6098. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6099. <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>
  6100. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6101. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6102. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6103. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6104. <td class="py-2.5 px-3 font-mono text-[11px]">
  6105. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6106. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6107. </td>
  6108. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6109. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6110. <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>
  6111. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6112. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6113. </td>
  6114. `;
  6115. tbody.appendChild(tr);
  6116. });
  6117. }
  6118. function openAddEoIPModal() {
  6119. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6120. document.getElementById('eoip-modal-id').value = '';
  6121. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6122. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6123. document.getElementById('eoip-modal-remote').value = '';
  6124. document.getElementById('eoip-modal-ip').value = '';
  6125. document.getElementById('eoip-modal-local').value = '';
  6126. document.getElementById('eoip-modal-mac').value = '';
  6127. document.getElementById('eoip-modal-mtu').value = '1500';
  6128. document.getElementById('eoip-modal-comment').value = '';
  6129. document.getElementById('eoip-modal-clampmss').checked = true;
  6130. document.getElementById('eoip-modal-disabled').checked = false;
  6131. document.getElementById('eoip-modal').classList.remove('hidden');
  6132. }
  6133. function openEditEoIPModal(id) {
  6134. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6135. if (!t) return;
  6136. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6137. document.getElementById('eoip-modal-id').value = t.id;
  6138. document.getElementById('eoip-modal-name').value = t.name;
  6139. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6140. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6141. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6142. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6143. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6144. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6145. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6146. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6147. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6148. document.getElementById('eoip-modal').classList.remove('hidden');
  6149. }
  6150. function closeEoIPModal() {
  6151. document.getElementById('eoip-modal').classList.add('hidden');
  6152. }
  6153. async function submitSaveEoIP(e) {
  6154. e.preventDefault();
  6155. const id = document.getElementById('eoip-modal-id').value;
  6156. const name = document.getElementById('eoip-modal-name').value.trim();
  6157. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6158. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6159. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6160. const local = document.getElementById('eoip-modal-local').value.trim();
  6161. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6162. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6163. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6164. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6165. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6166. try {
  6167. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6168. method: 'POST',
  6169. headers: { 'Content-Type': 'application/json' },
  6170. body: JSON.stringify({
  6171. id,
  6172. name,
  6173. tunnel_id: tunnelId,
  6174. remote_address: remote,
  6175. ip_address: ipAddress,
  6176. local_address: local,
  6177. mac_address: mac,
  6178. mtu,
  6179. clamp_mss: clampMss,
  6180. comment,
  6181. disabled
  6182. })
  6183. });
  6184. if (res.ok) {
  6185. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6186. closeEoIPModal();
  6187. loadEoIP(false);
  6188. fetchData(false);
  6189. } else {
  6190. const err = await res.json();
  6191. showToast('Error', err.message, 'error');
  6192. }
  6193. } catch (err) {
  6194. showToast('Error', err.message, 'error');
  6195. }
  6196. }
  6197. async function toggleEoIPState(id, disabled) {
  6198. try {
  6199. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6200. method: 'POST',
  6201. headers: { 'Content-Type': 'application/json' },
  6202. body: JSON.stringify({ disabled })
  6203. });
  6204. if (res.ok) {
  6205. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6206. loadEoIP(false);
  6207. fetchData(false);
  6208. }
  6209. } catch (err) {
  6210. showToast('Error', err.message, 'error');
  6211. }
  6212. }
  6213. async function deleteEoIP(id) {
  6214. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6215. try {
  6216. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6217. if (res.ok) {
  6218. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6219. loadEoIP(false);
  6220. fetchData(false);
  6221. }
  6222. } catch (err) {
  6223. showToast('Error', err.message, 'error');
  6224. }
  6225. }
  6226. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6227. async function loadAeroTUN(populate = true) {
  6228. try {
  6229. const [tunnelsRes, statsRes] = await Promise.all([
  6230. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6231. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6232. ]);
  6233. if (tunnelsRes.ok) {
  6234. const data = await tunnelsRes.json();
  6235. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6236. }
  6237. if (statsRes.ok) {
  6238. state.aerotunStats = await statsRes.json();
  6239. }
  6240. const countBadge = document.getElementById('aerotun-count-badge');
  6241. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6242. const sideBadge = document.getElementById('badge-aerotun-count');
  6243. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6244. renderAeroTUN();
  6245. } catch (err) {
  6246. console.error('Failed to load AeroTUN:', err);
  6247. }
  6248. }
  6249. function renderAeroTUN() {
  6250. const tbody = document.getElementById('aerotun-table-body');
  6251. const empty = document.getElementById('aerotun-empty');
  6252. // Update summary cards
  6253. const stats = state.aerotunStats || {};
  6254. const tunnels = state.aerotunTunnels || [];
  6255. const statActive = document.getElementById('aerotun-stat-active');
  6256. if (statActive) {
  6257. const activeCount = tunnels.filter(t => t.running).length;
  6258. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6259. }
  6260. const statSaved = document.getElementById('aerotun-stat-saved');
  6261. if (statSaved) {
  6262. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6263. }
  6264. const statRatio = document.getElementById('aerotun-stat-ratio');
  6265. if (statRatio) {
  6266. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6267. }
  6268. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6269. if (statTraffic) {
  6270. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6271. }
  6272. if (!tbody) return;
  6273. tbody.innerHTML = '';
  6274. if (tunnels.length === 0) {
  6275. empty?.classList.remove('hidden');
  6276. return;
  6277. }
  6278. empty?.classList.add('hidden');
  6279. tunnels.forEach(t => {
  6280. const tr = document.createElement('tr');
  6281. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6282. const modeBadge = t.mode === 'server'
  6283. ? `<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>`
  6284. : `<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>`;
  6285. const endpointInfo = t.mode === 'server'
  6286. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6287. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6288. const compBadge = t.compression
  6289. ? `<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>`
  6290. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6291. const activePeer = t.active_peer_endpoint
  6292. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6293. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6294. const rawRx = formatBytes(t.rx_bytes || 0);
  6295. const rawTx = formatBytes(t.tx_bytes || 0);
  6296. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6297. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6298. tr.innerHTML = `
  6299. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6300. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6301. <span>${escapeHtml(t.name)}</span>
  6302. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6303. </td>
  6304. <td class="py-2.5 px-3">${modeBadge}</td>
  6305. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6306. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6307. <td class="py-2.5 px-3">${compBadge}</td>
  6308. <td class="py-2.5 px-3">${activePeer}</td>
  6309. <td class="py-2.5 px-3 font-mono text-[11px]">
  6310. <span class="text-emerald-400">↓ ${rawRx}</span>
  6311. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6312. </td>
  6313. <td class="py-2.5 px-3 font-mono text-[11px]">
  6314. <span class="text-slate-400">↓ ${wireRx}</span>
  6315. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6316. </td>
  6317. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6318. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6319. ${t.running
  6320. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6321. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6322. }
  6323. <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>
  6324. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6325. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6326. </td>
  6327. `;
  6328. tbody.appendChild(tr);
  6329. });
  6330. }
  6331. function onAeroTUNModeChange() {
  6332. const mode = document.getElementById('aerotun-modal-mode').value;
  6333. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6334. const portInput = document.getElementById('aerotun-modal-port');
  6335. if (mode === 'server') {
  6336. if (!portInput.value) portInput.value = '51830';
  6337. endpointInput.placeholder = 'Optional / learned roaming peer';
  6338. } else {
  6339. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6340. if (!portInput.value) portInput.value = '';
  6341. }
  6342. }
  6343. async function generateAeroTUNKey() {
  6344. try {
  6345. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6346. if (res.ok) {
  6347. const data = await res.json();
  6348. document.getElementById('aerotun-modal-psk').value = data.key;
  6349. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6350. }
  6351. } catch (err) {
  6352. const arr = new Uint8Array(32);
  6353. crypto.getRandomValues(arr);
  6354. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6355. document.getElementById('aerotun-modal-psk').value = hex;
  6356. }
  6357. }
  6358. function openAddAeroTUNModal() {
  6359. const tunnels = state.aerotunTunnels || [];
  6360. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6361. document.getElementById('aerotun-modal-id').value = '';
  6362. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6363. document.getElementById('aerotun-modal-mode').value = 'server';
  6364. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6365. document.getElementById('aerotun-modal-endpoint').value = '';
  6366. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6367. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6368. document.getElementById('aerotun-modal-psk').value = '';
  6369. document.getElementById('aerotun-modal-mtu').value = '1420';
  6370. document.getElementById('aerotun-modal-comment').value = '';
  6371. document.getElementById('aerotun-modal-compression').checked = true;
  6372. document.getElementById('aerotun-modal-defroute').checked = false;
  6373. document.getElementById('aerotun-modal-disabled').checked = false;
  6374. generateAeroTUNKey();
  6375. onAeroTUNModeChange();
  6376. document.getElementById('aerotun-modal').classList.remove('hidden');
  6377. }
  6378. function openEditAeroTUNModal(id) {
  6379. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6380. if (!t) return;
  6381. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6382. document.getElementById('aerotun-modal-id').value = t.id;
  6383. document.getElementById('aerotun-modal-name').value = t.name;
  6384. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6385. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6386. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6387. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6388. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6389. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6390. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6391. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6392. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6393. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6394. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6395. onAeroTUNModeChange();
  6396. document.getElementById('aerotun-modal').classList.remove('hidden');
  6397. }
  6398. function closeAeroTUNModal() {
  6399. document.getElementById('aerotun-modal').classList.add('hidden');
  6400. }
  6401. async function submitSaveAeroTUN(e) {
  6402. e.preventDefault();
  6403. const id = document.getElementById('aerotun-modal-id').value;
  6404. const name = document.getElementById('aerotun-modal-name').value.trim();
  6405. const mode = document.getElementById('aerotun-modal-mode').value;
  6406. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6407. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6408. const local = document.getElementById('aerotun-modal-local').value.trim();
  6409. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6410. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6411. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6412. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6413. const compression = document.getElementById('aerotun-modal-compression').checked;
  6414. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6415. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6416. if (mode === 'client' && !endpoint) {
  6417. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6418. return;
  6419. }
  6420. if (!psk) {
  6421. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6422. return;
  6423. }
  6424. try {
  6425. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6426. method: 'POST',
  6427. headers: { 'Content-Type': 'application/json' },
  6428. body: JSON.stringify({
  6429. id,
  6430. name,
  6431. mode,
  6432. listen_port: port,
  6433. remote_endpoint: endpoint,
  6434. local_address: local,
  6435. peer_address: peer,
  6436. psk,
  6437. mtu,
  6438. compression,
  6439. default_route: defaultRoute,
  6440. comment,
  6441. disabled
  6442. })
  6443. });
  6444. if (res.ok) {
  6445. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6446. closeAeroTUNModal();
  6447. loadAeroTUN(false);
  6448. fetchData(false);
  6449. } else {
  6450. const err = await res.text();
  6451. showToast('Error Saving Tunnel', err, 'error');
  6452. }
  6453. } catch (err) {
  6454. showToast('Network Error', err.message, 'error');
  6455. }
  6456. }
  6457. async function startAeroTUNTunnel(id) {
  6458. try {
  6459. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6460. if (res.ok) {
  6461. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6462. loadAeroTUN(false);
  6463. fetchData(false);
  6464. } else {
  6465. const err = await res.text();
  6466. showToast('Failed to Start', err, 'error');
  6467. }
  6468. } catch (err) {
  6469. showToast('Error', err.message, 'error');
  6470. }
  6471. }
  6472. async function stopAeroTUNTunnel(id) {
  6473. try {
  6474. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6475. if (res.ok) {
  6476. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6477. loadAeroTUN(false);
  6478. fetchData(false);
  6479. } else {
  6480. const err = await res.text();
  6481. showToast('Failed to Stop', err, 'error');
  6482. }
  6483. } catch (err) {
  6484. showToast('Error', err.message, 'error');
  6485. }
  6486. }
  6487. async function toggleAeroTUNState(id, disabled) {
  6488. try {
  6489. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6490. method: 'POST',
  6491. headers: { 'Content-Type': 'application/json' },
  6492. body: JSON.stringify({ disabled })
  6493. });
  6494. if (res.ok) {
  6495. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6496. loadAeroTUN(false);
  6497. fetchData(false);
  6498. }
  6499. } catch (err) {
  6500. showToast('Error', err.message, 'error');
  6501. }
  6502. }
  6503. async function deleteAeroTUN(id) {
  6504. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6505. try {
  6506. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6507. if (res.ok) {
  6508. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6509. loadAeroTUN(false);
  6510. fetchData(false);
  6511. }
  6512. } catch (err) {
  6513. showToast('Error', err.message, 'error');
  6514. }
  6515. }
  6516. // ======================== PPP Central Hub & Servers ========================
  6517. function switchPPPSubTab(tab) {
  6518. state.pppSubTab = tab;
  6519. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6520. tabs.forEach(t => {
  6521. const panel = document.getElementById(`ppp-subtab-${t}`);
  6522. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6523. if (panel) {
  6524. if (t === tab) panel.classList.remove('hidden');
  6525. else panel.classList.add('hidden');
  6526. }
  6527. if (btn) {
  6528. if (t === tab) {
  6529. 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';
  6530. } else {
  6531. 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';
  6532. }
  6533. }
  6534. });
  6535. const addBtn = document.getElementById('ppp-primary-add-btn');
  6536. if (addBtn) {
  6537. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6538. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6539. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6540. else addBtn.innerHTML = '<span>Save Config</span>';
  6541. }
  6542. if (tab === 'active') loadPPPSessions();
  6543. }
  6544. function openCurrentPPPModal() {
  6545. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6546. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6547. else if (state.pppSubTab === 'active') loadPPPSessions();
  6548. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6549. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6550. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6551. }
  6552. async function loadPPP(populateDropdowns = true) {
  6553. await Promise.all([
  6554. loadPPPSecrets(),
  6555. loadPPPProfiles(),
  6556. loadPPPServers(),
  6557. loadPPPSessions()
  6558. ]);
  6559. }
  6560. async function loadPPPSecrets() {
  6561. try {
  6562. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6563. const data = await res.json();
  6564. state.pppSecrets = Array.isArray(data) ? data : [];
  6565. const b = document.getElementById('ppp-badge-secrets');
  6566. if (b) b.innerText = state.pppSecrets.length;
  6567. const b2 = document.getElementById('secrets-count-badge');
  6568. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6569. renderPPPSecrets();
  6570. } catch (err) {
  6571. console.error('Failed to load PPP secrets:', err);
  6572. }
  6573. }
  6574. function renderPPPSecrets() {
  6575. const tbody = document.getElementById('secrets-table-body');
  6576. const empty = document.getElementById('secrets-empty');
  6577. if (!tbody) return;
  6578. tbody.innerHTML = '';
  6579. const secrets = state.pppSecrets || [];
  6580. if (secrets.length === 0) {
  6581. empty?.classList.remove('hidden');
  6582. return;
  6583. }
  6584. empty?.classList.add('hidden');
  6585. secrets.forEach(s => {
  6586. const tr = document.createElement('tr');
  6587. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6588. tr.innerHTML = `
  6589. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6590. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6591. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6592. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6593. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6594. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6595. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6596. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6597. <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>
  6598. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6599. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6600. </td>
  6601. `;
  6602. tbody.appendChild(tr);
  6603. });
  6604. }
  6605. async function loadPPPProfiles() {
  6606. try {
  6607. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6608. const data = await res.json();
  6609. state.pppProfiles = Array.isArray(data) ? data : [];
  6610. const b = document.getElementById('ppp-badge-profiles');
  6611. if (b) b.innerText = state.pppProfiles.length;
  6612. const b2 = document.getElementById('profiles-count-badge');
  6613. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6614. // Populate profile selects across modals
  6615. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6616. selects.forEach(sid => {
  6617. const el = document.getElementById(sid);
  6618. if (!el) return;
  6619. const cur = el.value;
  6620. el.innerHTML = '';
  6621. state.pppProfiles.forEach(p => {
  6622. const opt = document.createElement('option');
  6623. opt.value = p.name;
  6624. opt.innerText = `${p.name} (${p.remote_address})`;
  6625. if (p.name === cur) opt.selected = true;
  6626. el.appendChild(opt);
  6627. });
  6628. });
  6629. renderPPPProfiles();
  6630. } catch (err) {
  6631. console.error('Failed to load PPP profiles:', err);
  6632. }
  6633. }
  6634. function renderPPPProfiles() {
  6635. const tbody = document.getElementById('profiles-table-body');
  6636. if (!tbody) return;
  6637. tbody.innerHTML = '';
  6638. (state.pppProfiles || []).forEach(p => {
  6639. const isDefault = p.name.startsWith('default');
  6640. const tr = document.createElement('tr');
  6641. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6642. tr.innerHTML = `
  6643. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6644. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6645. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6646. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6647. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6648. <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>
  6649. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6650. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6651. ${!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>`}
  6652. </td>
  6653. `;
  6654. tbody.appendChild(tr);
  6655. });
  6656. }
  6657. async function loadPPPServers() {
  6658. try {
  6659. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6660. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6661. fetch(`${API_BASE}/vpn/servers/pptp`),
  6662. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6663. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6664. ]);
  6665. if (pppoeRes.ok) {
  6666. state.pppoeServer = await pppoeRes.json();
  6667. const s = state.pppoeServer;
  6668. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6669. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6670. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6671. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6672. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6673. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6674. const pill = document.getElementById('pppoe-server-status-pill');
  6675. if (pill) {
  6676. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6677. 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';
  6678. }
  6679. setDotBadge('ppp-badge-pppoe-state', s.running);
  6680. }
  6681. if (pptpRes.ok) {
  6682. state.pptpServer = await pptpRes.json();
  6683. const s = state.pptpServer;
  6684. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6685. document.getElementById('pptp-server-port').value = s.port || 1723;
  6686. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6687. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6688. const pill = document.getElementById('pptp-server-status-pill');
  6689. if (pill) {
  6690. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6691. 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';
  6692. }
  6693. setDotBadge('ppp-badge-pptp-state', s.running);
  6694. }
  6695. if (l2tpRes.ok) {
  6696. state.l2tpServer = await l2tpRes.json();
  6697. const s = state.l2tpServer;
  6698. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6699. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6700. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6701. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6702. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6703. const pill = document.getElementById('l2tp-server-status-pill');
  6704. if (pill) {
  6705. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6706. 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';
  6707. }
  6708. setDotBadge('ppp-badge-l2tp-state', s.running);
  6709. }
  6710. if (ipsecRes.ok) {
  6711. state.ipsecServer = await ipsecRes.json();
  6712. const s = state.ipsecServer;
  6713. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6714. if (modalEn) modalEn.checked = !!s.enabled;
  6715. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6716. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6717. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6718. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6719. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6720. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6721. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6722. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6723. const pill = document.getElementById('modal-ipsec-server-status');
  6724. if (pill) {
  6725. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6726. 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';
  6727. }
  6728. }
  6729. } catch (err) {
  6730. console.error('Failed to load VPN servers:', err);
  6731. }
  6732. }
  6733. async function loadPPPSessions() {
  6734. try {
  6735. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6736. const data = await res.json();
  6737. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6738. const b = document.getElementById('ppp-badge-active');
  6739. if (b) b.innerText = state.pppActiveSessions.length;
  6740. const sideB = document.getElementById('badge-ppp-sessions');
  6741. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6742. renderPPPSessions();
  6743. } catch (err) {
  6744. console.error('Failed to load active PPP sessions:', err);
  6745. }
  6746. }
  6747. function renderPPPSessions() {
  6748. const tbody = document.getElementById('active-ppp-table-body');
  6749. const empty = document.getElementById('active-ppp-empty');
  6750. if (!tbody) return;
  6751. tbody.innerHTML = '';
  6752. const list = state.pppActiveSessions || [];
  6753. if (list.length === 0) {
  6754. empty?.classList.remove('hidden');
  6755. return;
  6756. }
  6757. empty?.classList.add('hidden');
  6758. list.forEach(s => {
  6759. const tr = document.createElement('tr');
  6760. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6761. tr.innerHTML = `
  6762. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6763. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6764. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6765. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6766. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6767. <td class="py-2.5 px-3 text-[11px]">
  6768. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6769. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6770. </td>
  6771. <td class="py-2.5 px-3 text-right font-sans">
  6772. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6773. </td>
  6774. `;
  6775. tbody.appendChild(tr);
  6776. });
  6777. }
  6778. async function disconnectPPPSession(iface) {
  6779. if (!confirm(`Disconnect session ${iface}?`)) return;
  6780. try {
  6781. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6782. if (res.ok) {
  6783. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6784. loadPPPSessions();
  6785. }
  6786. } catch (err) {
  6787. showToast('Error', err.message, 'error');
  6788. }
  6789. }
  6790. // PPP Secret Modal handlers
  6791. function openAddPPPSecretModal() {
  6792. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6793. document.getElementById('secret-modal-id').value = '';
  6794. document.getElementById('secret-modal-name').value = '';
  6795. document.getElementById('secret-modal-password').value = '';
  6796. document.getElementById('secret-modal-service').value = 'any';
  6797. document.getElementById('secret-modal-profile').value = 'default';
  6798. document.getElementById('secret-modal-local').value = '';
  6799. document.getElementById('secret-modal-remote').value = '';
  6800. document.getElementById('secret-modal-comment').value = '';
  6801. document.getElementById('secret-modal-disabled').checked = false;
  6802. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6803. }
  6804. function openEditPPPSecretModal(id) {
  6805. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6806. if (!s) return;
  6807. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6808. document.getElementById('secret-modal-id').value = s.id;
  6809. document.getElementById('secret-modal-name').value = s.name;
  6810. document.getElementById('secret-modal-password').value = s.password;
  6811. document.getElementById('secret-modal-service').value = s.service || 'any';
  6812. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6813. document.getElementById('secret-modal-local').value = s.local_address || '';
  6814. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6815. document.getElementById('secret-modal-comment').value = s.comment || '';
  6816. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6817. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6818. }
  6819. function closePPPSecretModal() {
  6820. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6821. }
  6822. async function submitSavePPPSecret(e) {
  6823. e.preventDefault();
  6824. const id = document.getElementById('secret-modal-id').value;
  6825. const name = document.getElementById('secret-modal-name').value.trim();
  6826. const password = document.getElementById('secret-modal-password').value.trim();
  6827. const service = document.getElementById('secret-modal-service').value;
  6828. const profile = document.getElementById('secret-modal-profile').value;
  6829. const local = document.getElementById('secret-modal-local').value.trim();
  6830. const remote = document.getElementById('secret-modal-remote').value.trim();
  6831. const comment = document.getElementById('secret-modal-comment').value.trim();
  6832. const disabled = document.getElementById('secret-modal-disabled').checked;
  6833. try {
  6834. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6835. method: 'POST',
  6836. headers: { 'Content-Type': 'application/json' },
  6837. body: JSON.stringify({
  6838. id,
  6839. name,
  6840. password,
  6841. service,
  6842. profile,
  6843. local_address: local,
  6844. remote_address: remote,
  6845. comment,
  6846. disabled
  6847. })
  6848. });
  6849. if (res.ok) {
  6850. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6851. closePPPSecretModal();
  6852. loadPPPSecrets();
  6853. } else {
  6854. const err = await res.json();
  6855. showToast('Error', err.message, 'error');
  6856. }
  6857. } catch (err) {
  6858. showToast('Error', err.message, 'error');
  6859. }
  6860. }
  6861. async function togglePPPSecretState(id, disabled) {
  6862. try {
  6863. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6864. method: 'POST',
  6865. headers: { 'Content-Type': 'application/json' },
  6866. body: JSON.stringify({ disabled })
  6867. });
  6868. if (res.ok) {
  6869. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6870. loadPPPSecrets();
  6871. }
  6872. } catch (err) {
  6873. showToast('Error', err.message, 'error');
  6874. }
  6875. }
  6876. async function deletePPPSecret(id) {
  6877. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6878. try {
  6879. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6880. if (res.ok) {
  6881. showToast('Deleted', 'Secret account removed', 'success');
  6882. loadPPPSecrets();
  6883. }
  6884. } catch (err) {
  6885. showToast('Error', err.message, 'error');
  6886. }
  6887. }
  6888. // PPP Profile Modal handlers
  6889. function openAddPPPProfileModal() {
  6890. document.getElementById('profile-modal-name').value = '';
  6891. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6892. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6893. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6894. document.getElementById('profile-modal-encryption').value = 'required';
  6895. document.getElementById('profile-modal-onlyone').checked = true;
  6896. document.getElementById('profile-modal-comment').value = '';
  6897. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6898. }
  6899. function closePPPProfileModal() {
  6900. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6901. }
  6902. async function submitSavePPPProfile(e) {
  6903. e.preventDefault();
  6904. const name = document.getElementById('profile-modal-name').value.trim();
  6905. const local = document.getElementById('profile-modal-local').value.trim();
  6906. const remote = document.getElementById('profile-modal-remote').value.trim();
  6907. const dns = document.getElementById('profile-modal-dns').value.trim();
  6908. const enc = document.getElementById('profile-modal-encryption').value;
  6909. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6910. const comment = document.getElementById('profile-modal-comment').value.trim();
  6911. try {
  6912. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6913. method: 'POST',
  6914. headers: { 'Content-Type': 'application/json' },
  6915. body: JSON.stringify({
  6916. id: name,
  6917. name,
  6918. local_address: local,
  6919. remote_address: remote,
  6920. dns_servers: dns,
  6921. use_encryption: enc,
  6922. only_one: onlyone,
  6923. comment
  6924. })
  6925. });
  6926. if (res.ok) {
  6927. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6928. closePPPProfileModal();
  6929. loadPPPProfiles();
  6930. } else {
  6931. const err = await res.json();
  6932. showToast('Error', err.message, 'error');
  6933. }
  6934. } catch (err) {
  6935. showToast('Error', err.message, 'error');
  6936. }
  6937. }
  6938. async function deletePPPProfile(name) {
  6939. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6940. try {
  6941. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6942. if (res.ok) {
  6943. showToast('Deleted', 'Profile removed', 'success');
  6944. loadPPPProfiles();
  6945. } else {
  6946. const err = await res.json();
  6947. showToast('Error', err.message, 'error');
  6948. }
  6949. } catch (err) {
  6950. showToast('Error', err.message, 'error');
  6951. }
  6952. }
  6953. // Server Config submissions
  6954. async function savePPPoEServerConfig(e) {
  6955. e.preventDefault();
  6956. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6957. const name = document.getElementById('pppoe-server-name').value.trim();
  6958. const iface = document.getElementById('pppoe-server-iface').value;
  6959. const profile = document.getElementById('pppoe-server-profile').value;
  6960. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6961. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6962. try {
  6963. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6964. method: 'POST',
  6965. headers: { 'Content-Type': 'application/json' },
  6966. body: JSON.stringify({
  6967. enabled,
  6968. service_name: name,
  6969. interface: iface,
  6970. default_profile: profile,
  6971. max_mtu: mtu,
  6972. max_mru: mtu,
  6973. one_session_per_host: onesession
  6974. })
  6975. });
  6976. if (res.ok) {
  6977. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6978. loadPPPServers();
  6979. fetchData(false);
  6980. } else {
  6981. const err = await res.json();
  6982. showToast('Error', err.message, 'error');
  6983. }
  6984. } catch (err) {
  6985. showToast('Error', err.message, 'error');
  6986. }
  6987. }
  6988. async function savePPTPServerConfig(e) {
  6989. e.preventDefault();
  6990. const enabled = document.getElementById('pptp-server-enabled').checked;
  6991. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6992. const profile = document.getElementById('pptp-server-profile').value;
  6993. const mppe = document.getElementById('pptp-server-mppe').checked;
  6994. try {
  6995. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6996. method: 'POST',
  6997. headers: { 'Content-Type': 'application/json' },
  6998. body: JSON.stringify({
  6999. enabled,
  7000. port,
  7001. default_profile: profile,
  7002. require_mppe: mppe
  7003. })
  7004. });
  7005. if (res.ok) {
  7006. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7007. loadPPPServers();
  7008. fetchData(false);
  7009. } else {
  7010. const err = await res.json();
  7011. showToast('Error', err.message, 'error');
  7012. }
  7013. } catch (err) {
  7014. showToast('Error', err.message, 'error');
  7015. }
  7016. }
  7017. async function saveL2TPServerConfig(e) {
  7018. e.preventDefault();
  7019. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7020. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7021. const profile = document.getElementById('l2tp-server-profile').value;
  7022. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7023. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7024. try {
  7025. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7026. method: 'POST',
  7027. headers: { 'Content-Type': 'application/json' },
  7028. body: JSON.stringify({
  7029. enabled,
  7030. port,
  7031. default_profile: profile,
  7032. use_ipsec: useipsec,
  7033. ipsec_secret: psk
  7034. })
  7035. });
  7036. if (res.ok) {
  7037. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7038. loadPPPServers();
  7039. fetchData(false);
  7040. } else {
  7041. const err = await res.json();
  7042. showToast('Error', err.message, 'error');
  7043. }
  7044. } catch (err) {
  7045. showToast('Error', err.message, 'error');
  7046. }
  7047. }
  7048. // IPSec Server Modal
  7049. function openIPSecServerModal() {
  7050. loadPPPServers();
  7051. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7052. }
  7053. function closeIPSecServerModal() {
  7054. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7055. }
  7056. async function submitSaveIPSecServer(e) {
  7057. e.preventDefault();
  7058. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7059. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7060. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7061. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7062. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7063. try {
  7064. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7065. method: 'POST',
  7066. headers: { 'Content-Type': 'application/json' },
  7067. body: JSON.stringify({
  7068. enabled,
  7069. preshared_key: psk,
  7070. pool_address: pool,
  7071. dns_servers: dns,
  7072. local_subnet: subnet
  7073. })
  7074. });
  7075. if (res.ok) {
  7076. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7077. closeIPSecServerModal();
  7078. loadPPPServers();
  7079. fetchData(false);
  7080. } else {
  7081. const err = await res.json();
  7082. showToast('Error', err.message, 'error');
  7083. }
  7084. } catch (err) {
  7085. showToast('Error', err.message, 'error');
  7086. }
  7087. }
  7088. // WireGuard Client Config Viewer
  7089. let currentWGClientConf = '';
  7090. async function openWGClientConfModal(iface, clientIP) {
  7091. try {
  7092. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7093. method: 'POST',
  7094. headers: { 'Content-Type': 'application/json' },
  7095. body: JSON.stringify({
  7096. interface: iface,
  7097. address: clientIP || '10.10.0.2/32',
  7098. dns: '1.1.1.1, 8.8.8.8'
  7099. })
  7100. });
  7101. if (res.ok) {
  7102. const data = await res.json();
  7103. currentWGClientConf = data.config;
  7104. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7105. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7106. } else {
  7107. const err = await res.json();
  7108. showToast('Error', err.message, 'error');
  7109. }
  7110. } catch (err) {
  7111. showToast('Error', err.message, 'error');
  7112. }
  7113. }
  7114. function closeWGClientConfModal() {
  7115. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7116. }
  7117. function copyWGClientConf() {
  7118. if (!currentWGClientConf) return;
  7119. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7120. }
  7121. function downloadWGClientConf() {
  7122. if (!currentWGClientConf) return;
  7123. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7124. const a = document.createElement('a');
  7125. a.href = URL.createObjectURL(blob);
  7126. a.download = 'wireguard-client.conf';
  7127. document.body.appendChild(a);
  7128. a.click();
  7129. document.body.removeChild(a);
  7130. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7131. }
  7132. // =========================================================================
  7133. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7134. // =========================================================================
  7135. state.activeDynSubTab = 'bgp-peers';
  7136. state.activeBgpSubTab = 'bgp-peers';
  7137. state.activeOspfTab = 'instances';
  7138. state.bgpInstance = null;
  7139. state.bgpPeers = [];
  7140. state.bgpNets = [];
  7141. state.bgpRoutes = [];
  7142. state.ospfInstance = null;
  7143. state.ospfInstances = [];
  7144. state.ospfAreas = [];
  7145. state.ospfAreaRanges = [];
  7146. state.ospfTemplates = [];
  7147. state.ospfLiveInterfaces = [];
  7148. state.ospfStaticNbrs = [];
  7149. state.ospfNeighbors = [];
  7150. state.ospfLSA = [];
  7151. state.ospfRoutes = [];
  7152. state.selectedOspfRow = {
  7153. instances: null,
  7154. areas: null,
  7155. 'area-ranges': null,
  7156. templates: null,
  7157. interfaces: null,
  7158. 'static-nbrs': null,
  7159. neighbors: null,
  7160. lsa: null,
  7161. };
  7162. state.ospfSort = {
  7163. instances: { col: 'name', asc: true },
  7164. areas: { col: 'name', asc: true },
  7165. ranges: { col: 'area', asc: true },
  7166. templates: { col: 'interfaces', asc: true },
  7167. live_ifaces: { col: 'interface', asc: true },
  7168. snbrs: { col: 'address', asc: true },
  7169. neighbors: { col: 'address', asc: true },
  7170. lsa: { col: 'instance', asc: true },
  7171. };
  7172. function switchBgpSubTab(subTab) {
  7173. state.activeBgpSubTab = subTab;
  7174. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7175. tabs.forEach(t => {
  7176. const el = document.getElementById(`dyn-subtab-${t}`);
  7177. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7178. if (el) el.classList.toggle('hidden', t !== subTab);
  7179. if (btn) {
  7180. if (t === subTab) {
  7181. 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';
  7182. } else {
  7183. 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';
  7184. }
  7185. }
  7186. });
  7187. }
  7188. function switchOspfTab(tabName) {
  7189. state.activeOspfTab = tabName;
  7190. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7191. tabs.forEach(t => {
  7192. const pane = document.getElementById(`ospf-pane-${t}`);
  7193. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7194. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7195. if (btn) {
  7196. if (t === tabName) {
  7197. 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';
  7198. } else {
  7199. 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';
  7200. }
  7201. }
  7202. });
  7203. }
  7204. function switchOspfSubTab(tab) {
  7205. // Legacy alias
  7206. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7207. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7208. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7209. else switchOspfTab('instances');
  7210. }
  7211. function switchDynSubTab(subTab) {
  7212. if (subTab.startsWith('bgp')) {
  7213. if (state.activeTab !== 'bgp') navigate('bgp');
  7214. switchBgpSubTab(subTab);
  7215. } else if (subTab.startsWith('ospf')) {
  7216. if (state.activeTab !== 'ospf') navigate('ospf');
  7217. switchOspfTab('instances');
  7218. }
  7219. }
  7220. async function loadDynamicRouting(showToastMsg = false) {
  7221. try {
  7222. const fetchSafeJson = async (url) => {
  7223. try {
  7224. const r = await fetch(url);
  7225. return r.ok ? await r.json() : null;
  7226. } catch (e) {
  7227. return null;
  7228. }
  7229. };
  7230. const [
  7231. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7232. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7233. selectRules, commLists, asLists
  7234. ] = await Promise.all([
  7235. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7236. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7237. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7238. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7239. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7240. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7241. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7242. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7243. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7244. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7245. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7246. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7247. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7248. fetchSafeJson(`${API_BASE}/routing/filters`),
  7249. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7250. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7251. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7252. ]);
  7253. if (sum) state.dynSummary = sum;
  7254. if (bgpInst) state.bgpInstance = bgpInst;
  7255. if (bgpPeers) state.bgpPeers = bgpPeers;
  7256. if (bgpNets) state.bgpNets = bgpNets;
  7257. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7258. if (ospfInsts) state.ospfInstances = ospfInsts;
  7259. if (ospfAreas) state.ospfAreas = ospfAreas;
  7260. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7261. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7262. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7263. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7264. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7265. if (ospfLsa) state.ospfLSA = ospfLsa;
  7266. if (filters) state.routingFilters = filters;
  7267. if (selectRules) state.routingSelectRules = selectRules;
  7268. if (commLists) state.routingCommunityLists = commLists;
  7269. if (asLists) state.routingASLists = asLists;
  7270. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7271. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7272. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7273. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7274. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7275. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7276. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7277. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7278. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7279. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7280. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7281. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7282. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7283. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7284. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7285. } catch (err) {
  7286. console.error('Failed to load dynamic routing:', err);
  7287. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7288. }
  7289. }
  7290. async function loadOspfAll() {
  7291. await loadDynamicRouting(true);
  7292. }
  7293. function renderBgpStatusPill() {
  7294. const pill = document.getElementById('bgp-live-status-pill');
  7295. if (!pill) return;
  7296. const inst = state.bgpInstance;
  7297. if (!inst || !inst.enabled) {
  7298. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7299. pill.innerText = 'BGP DISABLED';
  7300. } else if (inst.running) {
  7301. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  7302. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7303. } else {
  7304. 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';
  7305. pill.innerText = 'BGP STARTING...';
  7306. }
  7307. }
  7308. function renderBgpPeers() {
  7309. const tbody = document.getElementById('bgp-peers-table-body');
  7310. if (!tbody) return;
  7311. const empty = document.getElementById('bgp-peers-empty');
  7312. const countBadge = document.getElementById('bgp-peers-count-badge');
  7313. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7314. const peers = state.bgpPeers || [];
  7315. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7316. if (navBadge) navBadge.innerText = peers.length;
  7317. if (peers.length === 0) {
  7318. tbody.innerHTML = '';
  7319. if (empty) empty.classList.remove('hidden');
  7320. return;
  7321. }
  7322. if (empty) empty.classList.add('hidden');
  7323. tbody.innerHTML = peers.map(p => {
  7324. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7325. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7326. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7327. let stateBadge = '';
  7328. if (p.disabled) {
  7329. 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>';
  7330. } else if (p.state === 'Established') {
  7331. 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>';
  7332. } else if (p.state === 'Connect' || p.state === 'Active') {
  7333. 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>`;
  7334. } else {
  7335. 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>`;
  7336. }
  7337. return `
  7338. <tr class="hover:bg-slate-800/40 transition">
  7339. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7340. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7341. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7342. <td class="py-2.5 px-3">
  7343. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7344. ${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>`}
  7345. </td>
  7346. <td class="py-2.5 px-3">${stateBadge}</td>
  7347. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7348. <td class="py-2.5 px-3 text-slate-300">
  7349. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7350. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7351. </td>
  7352. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7353. ${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> ` : ''}
  7354. ${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>` : ''}
  7355. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7356. </td>
  7357. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7358. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7359. <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'}">
  7360. ${p.disabled ? 'Enable' : 'Disable'}
  7361. </button>
  7362. <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">
  7363. Edit
  7364. </button>
  7365. <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">
  7366. Delete
  7367. </button>
  7368. </td>
  7369. </tr>
  7370. `;
  7371. }).join('');
  7372. }
  7373. function renderBgpNetworks() {
  7374. const tbody = document.getElementById('bgp-nets-table-body');
  7375. if (!tbody) return;
  7376. const empty = document.getElementById('bgp-nets-empty');
  7377. const countBadge = document.getElementById('bgp-nets-count-badge');
  7378. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7379. const nets = state.bgpNets || [];
  7380. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7381. if (navBadge) navBadge.innerText = nets.length;
  7382. if (nets.length === 0) {
  7383. tbody.innerHTML = '';
  7384. if (empty) empty.classList.remove('hidden');
  7385. return;
  7386. }
  7387. if (empty) empty.classList.add('hidden');
  7388. tbody.innerHTML = nets.map(n => `
  7389. <tr class="hover:bg-slate-800/40 transition">
  7390. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7391. <td class="py-2.5 px-3">
  7392. ${n.disabled
  7393. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7394. : '<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>'}
  7395. </td>
  7396. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7397. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7398. <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">
  7399. Delete
  7400. </button>
  7401. </td>
  7402. </tr>
  7403. `).join('');
  7404. }
  7405. function renderBgpRoutes() {
  7406. const tbody = document.getElementById('bgp-routes-table-body');
  7407. if (!tbody) return;
  7408. const empty = document.getElementById('bgp-routes-empty');
  7409. const countBadge = document.getElementById('bgp-routes-count-badge');
  7410. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7411. const routes = state.bgpRoutes || [];
  7412. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7413. if (navBadge) navBadge.innerText = routes.length;
  7414. if (routes.length === 0) {
  7415. tbody.innerHTML = '';
  7416. if (empty) empty.classList.remove('hidden');
  7417. return;
  7418. }
  7419. if (empty) empty.classList.add('hidden');
  7420. tbody.innerHTML = routes.map(r => `
  7421. <tr class="hover:bg-slate-800/40 transition">
  7422. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7423. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7424. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7425. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7426. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7427. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7428. </tr>
  7429. `).join('');
  7430. }
  7431. // =========================================================================
  7432. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7433. // =========================================================================
  7434. function sortOspfTable(tab, col) {
  7435. if (!state.ospfSort) state.ospfSort = {};
  7436. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7437. if (state.ospfSort[tab].col === col) {
  7438. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7439. } else {
  7440. state.ospfSort[tab].col = col;
  7441. state.ospfSort[tab].asc = true;
  7442. }
  7443. const asc = state.ospfSort[tab].asc;
  7444. let list = [];
  7445. if (tab === 'instances') list = state.ospfInstances || [];
  7446. else if (tab === 'areas') list = state.ospfAreas || [];
  7447. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7448. else if (tab === 'templates') list = state.ospfTemplates || [];
  7449. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7450. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7451. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7452. else if (tab === 'lsa') list = state.ospfLSA || [];
  7453. list.sort((a, b) => {
  7454. let valA = a[col] ?? '';
  7455. let valB = b[col] ?? '';
  7456. if (typeof valA === 'number' && typeof valB === 'number') {
  7457. return asc ? valA - valB : valB - valA;
  7458. }
  7459. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7460. });
  7461. if (tab === 'instances') renderOspfInstances();
  7462. else if (tab === 'areas') renderOspfAreas();
  7463. else if (tab === 'ranges') renderOspfAreaRanges();
  7464. else if (tab === 'templates') renderOspfTemplates();
  7465. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7466. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7467. else if (tab === 'neighbors') renderOspfNeighbors();
  7468. else if (tab === 'lsa') renderOspfLSA();
  7469. }
  7470. function selectOspfRow(tab, id) {
  7471. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7472. state.selectedOspfRow[tab] = id;
  7473. if (tab === 'instances') {
  7474. renderOspfInstances();
  7475. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7476. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7477. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7478. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7479. if (btnEn) btnEn.disabled = false;
  7480. if (btnDis) btnDis.disabled = false;
  7481. if (btnRem) btnRem.disabled = false;
  7482. if (btnCom) btnCom.disabled = false;
  7483. } else if (tab === 'areas') {
  7484. renderOspfAreas();
  7485. const btnEn = document.getElementById('btn-ospf-area-enable');
  7486. const btnDis = document.getElementById('btn-ospf-area-disable');
  7487. const btnRem = document.getElementById('btn-ospf-area-remove');
  7488. const btnCom = document.getElementById('btn-ospf-area-comment');
  7489. if (btnEn) btnEn.disabled = false;
  7490. if (btnDis) btnDis.disabled = false;
  7491. if (btnRem) btnRem.disabled = false;
  7492. if (btnCom) btnCom.disabled = false;
  7493. } else if (tab === 'ranges') {
  7494. renderOspfAreaRanges();
  7495. const btnEn = document.getElementById('btn-ospf-range-enable');
  7496. const btnDis = document.getElementById('btn-ospf-range-disable');
  7497. const btnRem = document.getElementById('btn-ospf-range-remove');
  7498. const btnCom = document.getElementById('btn-ospf-range-comment');
  7499. if (btnEn) btnEn.disabled = false;
  7500. if (btnDis) btnDis.disabled = false;
  7501. if (btnRem) btnRem.disabled = false;
  7502. if (btnCom) btnCom.disabled = false;
  7503. } else if (tab === 'templates') {
  7504. renderOspfTemplates();
  7505. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7506. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7507. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7508. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7509. if (btnEn) btnEn.disabled = false;
  7510. if (btnDis) btnDis.disabled = false;
  7511. if (btnRem) btnRem.disabled = false;
  7512. if (btnCom) btnCom.disabled = false;
  7513. } else if (tab === 'snbrs') {
  7514. renderOspfStaticNbrs();
  7515. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7516. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7517. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7518. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7519. if (btnEn) btnEn.disabled = false;
  7520. if (btnDis) btnDis.disabled = false;
  7521. if (btnRem) btnRem.disabled = false;
  7522. if (btnCom) btnCom.disabled = false;
  7523. }
  7524. }
  7525. // TAB 1: INSTANCES
  7526. function renderOspfInstances() {
  7527. const tbody = document.getElementById('ospf-instances-table-body');
  7528. if (!tbody) return;
  7529. const countEl = document.getElementById('ospf-instances-footer-count');
  7530. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7531. let list = state.ospfInstances || [];
  7532. if (filter) {
  7533. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7534. }
  7535. if (countEl) countEl.innerText = list.length;
  7536. const selId = state.selectedOspfRow?.instances;
  7537. tbody.innerHTML = list.map((inst, idx) => {
  7538. const isSel = inst.id === selId;
  7539. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7540. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7541. return `
  7542. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7543. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7544. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7545. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7546. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7547. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7548. </td>
  7549. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7550. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7551. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7552. </tr>
  7553. `;
  7554. }).join('');
  7555. }
  7556. // TAB 2: AREAS
  7557. function renderOspfAreas() {
  7558. const tbody = document.getElementById('ospf-areas-table-body');
  7559. if (!tbody) return;
  7560. const countEl = document.getElementById('ospf-areas-footer-count');
  7561. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7562. let list = state.ospfAreas || [];
  7563. if (filter) {
  7564. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7565. }
  7566. if (countEl) countEl.innerText = list.length;
  7567. const selId = state.selectedOspfRow?.areas;
  7568. tbody.innerHTML = list.map((a, idx) => {
  7569. const isSel = a.id === selId;
  7570. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7571. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7572. return `
  7573. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7574. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7575. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7576. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7577. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7578. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7579. </td>
  7580. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7581. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7582. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7583. </tr>
  7584. `;
  7585. }).join('');
  7586. }
  7587. // TAB 3: AREA RANGES
  7588. function renderOspfAreaRanges() {
  7589. const tbody = document.getElementById('ospf-ranges-table-body');
  7590. if (!tbody) return;
  7591. const countEl = document.getElementById('ospf-ranges-footer-count');
  7592. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7593. let list = state.ospfAreaRanges || [];
  7594. if (filter) {
  7595. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7596. }
  7597. if (countEl) countEl.innerText = list.length;
  7598. const selId = state.selectedOspfRow?.['area-ranges'];
  7599. tbody.innerHTML = list.map((r, idx) => {
  7600. const isSel = r.id === selId;
  7601. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7602. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7603. return `
  7604. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7605. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7606. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7607. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7608. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7609. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7610. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7611. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7612. </tr>
  7613. `;
  7614. }).join('');
  7615. }
  7616. // TAB 4: INTERFACE TEMPLATES
  7617. function renderOspfTemplates() {
  7618. const tbody = document.getElementById('ospf-templates-table-body');
  7619. if (!tbody) return;
  7620. const countEl = document.getElementById('ospf-templates-footer-count');
  7621. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7622. let list = state.ospfTemplates || [];
  7623. if (filter) {
  7624. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7625. }
  7626. if (countEl) countEl.innerText = list.length;
  7627. const selId = state.selectedOspfRow?.templates;
  7628. tbody.innerHTML = list.map((t, idx) => {
  7629. const isSel = t.id === selId;
  7630. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7631. const ifaces = t.interfaces || t.interface || 'all';
  7632. const nets = t.networks || t.network || '';
  7633. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7634. return `
  7635. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7636. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7637. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7638. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7639. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7640. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7641. </td>
  7642. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7643. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7644. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7645. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7646. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7647. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7648. </tr>
  7649. `;
  7650. }).join('');
  7651. }
  7652. // TAB 5: LIVE INTERFACES
  7653. function renderOspfLiveInterfaces() {
  7654. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7655. if (!tbody) return;
  7656. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7657. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7658. let list = state.ospfLiveInterfaces || [];
  7659. if (filter) {
  7660. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7661. }
  7662. if (countEl) countEl.innerText = list.length;
  7663. tbody.innerHTML = list.map(i => `
  7664. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7665. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7666. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7667. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7668. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7669. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7670. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7671. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7672. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7673. </tr>
  7674. `).join('');
  7675. }
  7676. // TAB 6: STATIC NEIGHBORS
  7677. function renderOspfStaticNbrs() {
  7678. const tbody = document.getElementById('ospf-snbrs-table-body');
  7679. if (!tbody) return;
  7680. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7681. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7682. let list = state.ospfStaticNbrs || [];
  7683. if (filter) {
  7684. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7685. }
  7686. if (countEl) countEl.innerText = list.length;
  7687. const selId = state.selectedOspfRow?.['static-nbrs'];
  7688. tbody.innerHTML = list.map((n, idx) => {
  7689. const isSel = n.id === selId;
  7690. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7691. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7692. return `
  7693. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7694. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7695. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7696. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7697. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7698. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7699. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7700. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7701. </tr>
  7702. `;
  7703. }).join('');
  7704. }
  7705. // TAB 7: LIVE NEIGHBORS
  7706. function renderOspfNeighbors() {
  7707. const tbody = document.getElementById('ospf-neighbors-table-body');
  7708. if (!tbody) return;
  7709. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7710. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7711. let list = state.ospfNeighbors || [];
  7712. if (filter) {
  7713. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7714. }
  7715. if (countEl) countEl.innerText = list.length;
  7716. tbody.innerHTML = list.map(n => `
  7717. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7718. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7719. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7720. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7721. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7722. </td>
  7723. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7724. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7725. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7726. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7727. </tr>
  7728. `).join('');
  7729. }
  7730. // TAB 8: LINK-STATE DATABASE (LSA)
  7731. function renderOspfLSA() {
  7732. const tbody = document.getElementById('ospf-lsa-table-body');
  7733. if (!tbody) return;
  7734. const countEl = document.getElementById('ospf-lsa-footer-count');
  7735. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7736. let list = state.ospfLSA || [];
  7737. if (filter) {
  7738. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7739. }
  7740. if (countEl) countEl.innerText = list.length;
  7741. tbody.innerHTML = list.map(l => `
  7742. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7743. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7744. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7745. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7746. </td>
  7747. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7748. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7749. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7750. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7751. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7752. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7753. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7754. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7755. </tr>
  7756. `).join('');
  7757. }
  7758. function renderOspfStatusPill() {
  7759. // Maintained for backward compatibility
  7760. const pill = document.getElementById('ospf-live-status-pill');
  7761. if (!pill) return;
  7762. 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';
  7763. pill.innerText = 'OSPF ACTIVE';
  7764. }
  7765. function renderOspfInterfaces() {
  7766. renderOspfTemplates();
  7767. }
  7768. function renderOspfRoutes() {
  7769. // Routes retained in background
  7770. }
  7771. // BGP Modals & Actions
  7772. function openBgpInstanceModal() {
  7773. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7774. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7775. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7776. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7777. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7778. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7779. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7780. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7781. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7782. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7783. }
  7784. function closeBgpInstanceModal() {
  7785. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7786. }
  7787. async function submitBgpInstance(e) {
  7788. e.preventDefault();
  7789. const payload = {
  7790. enabled: document.getElementById('modal-bgp-enabled').checked,
  7791. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7792. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7793. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7794. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7795. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7796. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7797. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7798. };
  7799. try {
  7800. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7801. method: 'POST',
  7802. headers: { 'Content-Type': 'application/json' },
  7803. body: JSON.stringify(payload)
  7804. });
  7805. if (res.ok) {
  7806. closeBgpInstanceModal();
  7807. showToast('Success', 'BGP instance configuration updated', 'success');
  7808. loadDynamicRouting();
  7809. } else {
  7810. const err = await res.json();
  7811. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7812. }
  7813. } catch (err) {
  7814. showToast('Error', err.message, 'error');
  7815. }
  7816. }
  7817. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7818. function switchBgpPeerModalTab(tab) {
  7819. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7820. tabs.forEach(t => {
  7821. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7822. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7823. if (t === tab) {
  7824. if (pane) pane.classList.remove('hidden');
  7825. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7826. } else {
  7827. if (pane) pane.classList.add('hidden');
  7828. 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';
  7829. }
  7830. });
  7831. }
  7832. function addOutputNetworkRow(val = '') {
  7833. const container = document.getElementById('modal-bgp-output-networks-container');
  7834. if (!container) return;
  7835. const row = document.createElement('div');
  7836. row.className = 'flex items-center gap-2 output-net-row';
  7837. row.innerHTML = `
  7838. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  7839. <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>
  7840. `;
  7841. container.appendChild(row);
  7842. }
  7843. function parseBgpTime(val) {
  7844. if (!val) return 0;
  7845. val = String(val).trim();
  7846. if (val.includes(':')) {
  7847. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7848. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7849. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7850. }
  7851. return parseInt(val, 10) || 0;
  7852. }
  7853. function formatBgpTime(secs) {
  7854. if (!secs || secs <= 0) return '00:00:00';
  7855. const h = Math.floor(secs / 3600);
  7856. const m = Math.floor((secs % 3600) / 60);
  7857. const s = secs % 60;
  7858. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7859. }
  7860. function populateBgpRoutingTables() {
  7861. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7862. if (!sel) return;
  7863. const cur = sel.value || 'main';
  7864. sel.innerHTML = '<option value="main">main</option>';
  7865. (state.routingTables || []).forEach(t => {
  7866. if (t.name !== 'main') {
  7867. const opt = document.createElement('option');
  7868. opt.value = t.name;
  7869. opt.innerText = t.name;
  7870. sel.appendChild(opt);
  7871. }
  7872. });
  7873. sel.value = cur;
  7874. }
  7875. function openAddBgpPeerModal() {
  7876. document.getElementById('bgp-peer-form').reset();
  7877. document.getElementById('modal-bgp-peer-id').value = '';
  7878. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7879. // General Tab
  7880. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7881. document.getElementById('modal-bgp-peer-comment').value = '';
  7882. document.getElementById('modal-bgp-peer-name').value = '';
  7883. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7884. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7885. document.getElementById('modal-bgp-peer-local-as').value = '';
  7886. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7887. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7888. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7889. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7890. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7891. document.getElementById('modal-bgp-peer-router-id').value = '';
  7892. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7893. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7894. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7895. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7896. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7897. document.getElementById('modal-bgp-peer-local-port').value = '';
  7898. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7899. document.getElementById('modal-bgp-peer-password').value = '';
  7900. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7901. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7902. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7903. document.getElementById('modal-bgp-peer-connect').checked = true;
  7904. document.getElementById('modal-bgp-peer-listen').checked = true;
  7905. // Extra Tab
  7906. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7907. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7908. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7909. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7910. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7911. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7912. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7913. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7914. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7915. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7916. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7917. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7918. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7919. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7920. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7921. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7922. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7923. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7924. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7925. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7926. // Attributes Tab
  7927. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7928. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7929. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7930. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7931. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7932. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7933. // Filter Tab
  7934. populateFilterChainsDatalist();
  7935. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7936. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7937. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7938. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7939. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7940. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7941. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7942. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7943. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7944. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7945. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7946. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7947. populateBgpRoutingTables();
  7948. const container = document.getElementById('modal-bgp-output-networks-container');
  7949. if (container) {
  7950. container.innerHTML = '';
  7951. addOutputNetworkRow('');
  7952. }
  7953. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7954. if (removeBtn) removeBtn.classList.add('hidden');
  7955. switchBgpPeerModalTab('general');
  7956. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7957. }
  7958. function populateFilterChainsDatalist() {
  7959. const dl = document.getElementById('filter-chains-list');
  7960. if (!dl) return;
  7961. const chains = new Set();
  7962. (state.routingFilters || []).forEach(f => {
  7963. if (f.chain) chains.add(f.chain);
  7964. });
  7965. if (chains.size === 0) {
  7966. chains.add('awmn');
  7967. chains.add('bgp-in');
  7968. chains.add('bgp-out');
  7969. }
  7970. dl.innerHTML = '';
  7971. chains.forEach(c => {
  7972. const opt = document.createElement('option');
  7973. opt.value = c;
  7974. dl.appendChild(opt);
  7975. });
  7976. }
  7977. function openEditBgpPeerModal(id) {
  7978. const p = (state.bgpPeers || []).find(item => item.id === id);
  7979. if (!p) return;
  7980. populateBgpRoutingTables();
  7981. populateFilterChainsDatalist();
  7982. document.getElementById('modal-bgp-peer-id').value = p.id;
  7983. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7984. // General Tab
  7985. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7986. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7987. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7988. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7989. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7990. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7991. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7992. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7993. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7994. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7995. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7996. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7997. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7998. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7999. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8000. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8001. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8002. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8003. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8004. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8005. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8006. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8007. // Extra Tab
  8008. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8009. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8010. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8011. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8012. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8013. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8014. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8015. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8016. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8017. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8018. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8019. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8020. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8021. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8022. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8023. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8024. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8025. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8026. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8027. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8028. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8029. // Attributes Tab
  8030. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8031. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8032. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8033. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8034. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8035. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8036. // Filter Tab
  8037. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8038. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8039. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8040. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8041. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8042. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8043. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8044. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8045. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8046. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8047. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8048. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8049. // Output Networks
  8050. const container = document.getElementById('modal-bgp-output-networks-container');
  8051. if (container) {
  8052. container.innerHTML = '';
  8053. if (p.output_networks && p.output_networks.length > 0) {
  8054. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8055. } else {
  8056. addOutputNetworkRow('');
  8057. }
  8058. }
  8059. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8060. if (removeBtn) removeBtn.classList.remove('hidden');
  8061. switchBgpPeerModalTab('general');
  8062. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8063. }
  8064. function copyCurrentBgpPeer() {
  8065. document.getElementById('modal-bgp-peer-id').value = '';
  8066. const nameEl = document.getElementById('modal-bgp-peer-name');
  8067. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8068. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8069. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8070. if (removeBtn) removeBtn.classList.add('hidden');
  8071. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8072. }
  8073. function removeCurrentBgpPeer() {
  8074. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8075. if (!id) return;
  8076. deleteBgpPeer(id);
  8077. closeBgpPeerModal();
  8078. }
  8079. function closeBgpPeerModal() {
  8080. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8081. }
  8082. function getBgpPeerFormData() {
  8083. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8084. const outputNetworks = [];
  8085. netInputs.forEach(inp => {
  8086. const v = inp.value.trim();
  8087. if (v) outputNetworks.push(v);
  8088. });
  8089. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8090. return {
  8091. id: document.getElementById('modal-bgp-peer-id').value,
  8092. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8093. enabled: enabled,
  8094. disabled: !enabled,
  8095. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8096. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8097. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8098. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8099. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8100. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8101. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8102. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8103. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8104. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8105. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8106. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8107. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8108. password: document.getElementById('modal-bgp-peer-password').value,
  8109. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8110. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8111. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8112. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8113. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8114. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8115. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8116. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8117. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8118. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8119. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8120. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8121. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8122. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8123. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8124. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8125. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8126. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8127. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8128. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8129. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8130. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8131. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8132. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8133. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8134. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8135. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8136. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8137. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8138. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8139. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8140. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8141. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8142. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8143. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8144. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8145. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8146. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8147. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8148. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8149. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8150. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8151. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8152. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8153. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8154. output_networks: outputNetworks
  8155. };
  8156. }
  8157. async function submitBgpPeer(e) {
  8158. if (e) e.preventDefault();
  8159. const payload = getBgpPeerFormData();
  8160. try {
  8161. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8162. method: 'POST',
  8163. headers: { 'Content-Type': 'application/json' },
  8164. body: JSON.stringify(payload)
  8165. });
  8166. if (res.ok) {
  8167. closeBgpPeerModal();
  8168. showToast('Success', 'BGP Connection saved', 'success');
  8169. loadDynamicRouting();
  8170. } else {
  8171. const err = await res.json();
  8172. showToast('Error', err.error || 'Failed to save peer', 'error');
  8173. }
  8174. } catch (err) {
  8175. showToast('Error', err.message, 'error');
  8176. }
  8177. }
  8178. async function applyBgpPeerModal(e) {
  8179. if (e) e.preventDefault();
  8180. const payload = getBgpPeerFormData();
  8181. try {
  8182. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8183. method: 'POST',
  8184. headers: { 'Content-Type': 'application/json' },
  8185. body: JSON.stringify(payload)
  8186. });
  8187. if (res.ok) {
  8188. const data = await res.json();
  8189. if (data.peer && data.peer.id) {
  8190. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8191. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8192. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8193. }
  8194. showToast('Applied', 'BGP Connection applied', 'success');
  8195. loadDynamicRouting();
  8196. } else {
  8197. const err = await res.json();
  8198. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8199. }
  8200. } catch (err) {
  8201. showToast('Error', err.message, 'error');
  8202. }
  8203. }
  8204. async function deleteBgpPeer(id) {
  8205. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8206. try {
  8207. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8208. if (res.ok) {
  8209. showToast('Deleted', 'BGP peer removed', 'success');
  8210. loadDynamicRouting();
  8211. }
  8212. } catch (err) {
  8213. showToast('Error', err.message, 'error');
  8214. }
  8215. }
  8216. async function toggleBgpPeerState(id, disabled) {
  8217. try {
  8218. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8219. method: 'POST',
  8220. headers: { 'Content-Type': 'application/json' },
  8221. body: JSON.stringify({ disabled })
  8222. });
  8223. if (res.ok) {
  8224. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8225. loadDynamicRouting();
  8226. }
  8227. } catch (err) {
  8228. showToast('Error', err.message, 'error');
  8229. }
  8230. }
  8231. function openAddBgpNetworkModal() {
  8232. document.getElementById('bgp-network-form').reset();
  8233. document.getElementById('modal-bgp-net-id').value = '';
  8234. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8235. }
  8236. function closeBgpNetworkModal() {
  8237. document.getElementById('bgp-network-modal').classList.add('hidden');
  8238. }
  8239. async function submitBgpNetwork(e) {
  8240. e.preventDefault();
  8241. const payload = {
  8242. id: document.getElementById('modal-bgp-net-id').value,
  8243. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8244. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8245. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8246. };
  8247. try {
  8248. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8249. method: 'POST',
  8250. headers: { 'Content-Type': 'application/json' },
  8251. body: JSON.stringify(payload)
  8252. });
  8253. if (res.ok) {
  8254. closeBgpNetworkModal();
  8255. showToast('Success', 'BGP network advertisement saved', 'success');
  8256. loadDynamicRouting();
  8257. } else {
  8258. const err = await res.json();
  8259. showToast('Error', err.error || 'Failed to save network', 'error');
  8260. }
  8261. } catch (err) {
  8262. showToast('Error', err.message, 'error');
  8263. }
  8264. }
  8265. async function deleteBgpNetwork(id) {
  8266. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8267. try {
  8268. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8269. if (res.ok) {
  8270. showToast('Deleted', 'Network advertisement removed', 'success');
  8271. loadDynamicRouting();
  8272. }
  8273. } catch (err) {
  8274. showToast('Error', err.message, 'error');
  8275. }
  8276. }
  8277. // =========================================================================
  8278. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8279. // =========================================================================
  8280. // --- 1. OSPF INSTANCE ---
  8281. function openOspfInstanceModal(id = null) {
  8282. const isEdit = !!id;
  8283. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8284. id: '',
  8285. name: 'Default',
  8286. version: 2,
  8287. vrf: 'main',
  8288. router_id: '192.168.131.56',
  8289. routing_table: 'main',
  8290. enabled: true,
  8291. redistribute_connected: false,
  8292. redistribute_static: true,
  8293. redistribute_bgp: false,
  8294. comment: ''
  8295. };
  8296. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8297. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8298. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8299. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8300. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8301. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8302. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8303. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8304. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8305. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8306. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8307. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8308. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8309. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8310. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8311. }
  8312. function openEditOspfInstanceModal(id) {
  8313. openOspfInstanceModal(id);
  8314. }
  8315. function closeOspfInstanceModal() {
  8316. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8317. }
  8318. async function submitOspfInstance(e) {
  8319. if (e) e.preventDefault();
  8320. const payload = {
  8321. id: document.getElementById('modal-ospf-inst-id').value,
  8322. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8323. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8324. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8325. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8326. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8327. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8328. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8329. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8330. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8331. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8332. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8333. };
  8334. try {
  8335. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8336. method: 'POST',
  8337. headers: { 'Content-Type': 'application/json' },
  8338. body: JSON.stringify(payload)
  8339. });
  8340. if (res.ok) {
  8341. closeOspfInstanceModal();
  8342. showToast('Saved', 'OSPF instance updated', 'success');
  8343. loadDynamicRouting();
  8344. } else {
  8345. const err = await res.json();
  8346. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8347. }
  8348. } catch (err) {
  8349. showToast('Error', err.message, 'error');
  8350. }
  8351. }
  8352. function applyOspfInstanceForm() {
  8353. submitOspfInstance(null);
  8354. }
  8355. function copyOspfInstance() {
  8356. document.getElementById('modal-ospf-inst-id').value = '';
  8357. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8358. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8359. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8360. }
  8361. async function deleteCurrentOspfInstance() {
  8362. const id = document.getElementById('modal-ospf-inst-id').value;
  8363. if (!id) return;
  8364. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8365. try {
  8366. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8367. if (res.ok) {
  8368. closeOspfInstanceModal();
  8369. showToast('Removed', 'OSPF instance deleted', 'success');
  8370. loadDynamicRouting();
  8371. }
  8372. } catch (err) {
  8373. showToast('Error', err.message, 'error');
  8374. }
  8375. }
  8376. async function enableSelectedOspfInstance() {
  8377. const id = state.selectedOspfRow?.instances;
  8378. if (!id) return;
  8379. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8380. method: 'POST',
  8381. headers: { 'Content-Type': 'application/json' },
  8382. body: JSON.stringify({ disabled: false })
  8383. });
  8384. loadDynamicRouting();
  8385. }
  8386. async function disableSelectedOspfInstance() {
  8387. const id = state.selectedOspfRow?.instances;
  8388. if (!id) return;
  8389. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8390. method: 'POST',
  8391. headers: { 'Content-Type': 'application/json' },
  8392. body: JSON.stringify({ disabled: true })
  8393. });
  8394. loadDynamicRouting();
  8395. }
  8396. async function removeSelectedOspfInstance() {
  8397. const id = state.selectedOspfRow?.instances;
  8398. if (!id) return;
  8399. if (!confirm('Delete selected OSPF instance?')) return;
  8400. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8401. loadDynamicRouting();
  8402. }
  8403. async function promptCommentOspfInstance() {
  8404. const id = state.selectedOspfRow?.instances;
  8405. if (!id) return;
  8406. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8407. if (!inst) return;
  8408. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8409. if (comment === null) return;
  8410. inst.comment = comment;
  8411. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8412. method: 'POST',
  8413. headers: { 'Content-Type': 'application/json' },
  8414. body: JSON.stringify(inst)
  8415. });
  8416. loadDynamicRouting();
  8417. }
  8418. // --- 2. OSPF AREA ---
  8419. function populateOspfAreaDropdowns() {
  8420. const instSelect = document.getElementById('modal-ospf-area-instance');
  8421. if (instSelect) {
  8422. const cur = instSelect.value;
  8423. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8424. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8425. if (cur) instSelect.value = cur;
  8426. }
  8427. }
  8428. function openOspfAreaModal(id = null) {
  8429. const isEdit = !!id;
  8430. populateOspfAreaDropdowns();
  8431. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8432. id: '',
  8433. name: 'Default',
  8434. instance: 'Default',
  8435. area_id: '0.0.0.0',
  8436. area_type: 'default',
  8437. default_cost: 1,
  8438. no_summaries: false,
  8439. disabled: false,
  8440. comment: ''
  8441. };
  8442. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8443. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8444. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8445. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8446. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8447. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8448. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8449. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8450. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8451. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8452. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8453. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8454. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8455. }
  8456. function openEditOspfAreaModal(id) {
  8457. openOspfAreaModal(id);
  8458. }
  8459. function closeOspfAreaModal() {
  8460. document.getElementById('ospf-area-modal').classList.add('hidden');
  8461. }
  8462. async function submitOspfArea(e) {
  8463. if (e) e.preventDefault();
  8464. const payload = {
  8465. id: document.getElementById('modal-ospf-area-id').value,
  8466. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8467. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8468. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8469. area_type: document.getElementById('modal-ospf-area-type').value,
  8470. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8471. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8472. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8473. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8474. };
  8475. try {
  8476. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8477. method: 'POST',
  8478. headers: { 'Content-Type': 'application/json' },
  8479. body: JSON.stringify(payload)
  8480. });
  8481. if (res.ok) {
  8482. closeOspfAreaModal();
  8483. showToast('Saved', 'OSPF area saved', 'success');
  8484. loadDynamicRouting();
  8485. } else {
  8486. const err = await res.json();
  8487. showToast('Error', err.error || 'Failed to save area', 'error');
  8488. }
  8489. } catch (err) {
  8490. showToast('Error', err.message, 'error');
  8491. }
  8492. }
  8493. function applyOspfAreaForm() {
  8494. submitOspfArea(null);
  8495. }
  8496. function copyOspfArea() {
  8497. document.getElementById('modal-ospf-area-id').value = '';
  8498. document.getElementById('modal-ospf-area-name').value += '-copy';
  8499. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8500. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8501. }
  8502. async function deleteCurrentOspfArea() {
  8503. const id = document.getElementById('modal-ospf-area-id').value;
  8504. if (!id) return;
  8505. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8506. try {
  8507. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8508. if (res.ok) {
  8509. closeOspfAreaModal();
  8510. showToast('Removed', 'OSPF area deleted', 'success');
  8511. loadDynamicRouting();
  8512. }
  8513. } catch (err) {
  8514. showToast('Error', err.message, 'error');
  8515. }
  8516. }
  8517. async function enableSelectedOspfArea() {
  8518. const id = state.selectedOspfRow?.areas;
  8519. if (!id) return;
  8520. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8521. method: 'POST',
  8522. headers: { 'Content-Type': 'application/json' },
  8523. body: JSON.stringify({ disabled: false })
  8524. });
  8525. loadDynamicRouting();
  8526. }
  8527. async function disableSelectedOspfArea() {
  8528. const id = state.selectedOspfRow?.areas;
  8529. if (!id) return;
  8530. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8531. method: 'POST',
  8532. headers: { 'Content-Type': 'application/json' },
  8533. body: JSON.stringify({ disabled: true })
  8534. });
  8535. loadDynamicRouting();
  8536. }
  8537. async function removeSelectedOspfArea() {
  8538. const id = state.selectedOspfRow?.areas;
  8539. if (!id) return;
  8540. if (!confirm('Delete selected OSPF area?')) return;
  8541. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8542. loadDynamicRouting();
  8543. }
  8544. async function promptCommentOspfArea() {
  8545. const id = state.selectedOspfRow?.areas;
  8546. if (!id) return;
  8547. const area = (state.ospfAreas || []).find(a => a.id === id);
  8548. if (!area) return;
  8549. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8550. if (comment === null) return;
  8551. area.comment = comment;
  8552. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8553. method: 'POST',
  8554. headers: { 'Content-Type': 'application/json' },
  8555. body: JSON.stringify(area)
  8556. });
  8557. loadDynamicRouting();
  8558. }
  8559. // --- 3. OSPF AREA RANGE ---
  8560. function populateAreaRangeDropdowns() {
  8561. const select = document.getElementById('modal-ospf-range-area');
  8562. if (select) {
  8563. const cur = select.value;
  8564. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8565. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8566. if (cur) select.value = cur;
  8567. }
  8568. }
  8569. function openOspfAreaRangeModal(id = null) {
  8570. const isEdit = !!id;
  8571. populateAreaRangeDropdowns();
  8572. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8573. id: '',
  8574. area: 'Default',
  8575. prefix: '',
  8576. cost: 1,
  8577. advertise: true,
  8578. disabled: false,
  8579. comment: ''
  8580. };
  8581. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8582. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8583. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8584. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8585. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8586. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8587. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8588. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8589. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8590. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8591. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8592. }
  8593. function openEditOspfAreaRangeModal(id) {
  8594. openOspfAreaRangeModal(id);
  8595. }
  8596. function closeOspfAreaRangeModal() {
  8597. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8598. }
  8599. async function submitOspfAreaRange(e) {
  8600. if (e) e.preventDefault();
  8601. const payload = {
  8602. id: document.getElementById('modal-ospf-range-id').value,
  8603. area: document.getElementById('modal-ospf-range-area').value,
  8604. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8605. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8606. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8607. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8608. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8609. };
  8610. try {
  8611. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8612. method: 'POST',
  8613. headers: { 'Content-Type': 'application/json' },
  8614. body: JSON.stringify(payload)
  8615. });
  8616. if (res.ok) {
  8617. closeOspfAreaRangeModal();
  8618. showToast('Saved', 'Area range saved', 'success');
  8619. loadDynamicRouting();
  8620. } else {
  8621. const err = await res.json();
  8622. showToast('Error', err.error || 'Failed to save area range', 'error');
  8623. }
  8624. } catch (err) {
  8625. showToast('Error', err.message, 'error');
  8626. }
  8627. }
  8628. function applyOspfAreaRangeForm() {
  8629. submitOspfAreaRange(null);
  8630. }
  8631. async function deleteCurrentOspfAreaRange() {
  8632. const id = document.getElementById('modal-ospf-range-id').value;
  8633. if (!id) return;
  8634. if (!confirm('Delete this area range?')) return;
  8635. try {
  8636. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8637. closeOspfAreaRangeModal();
  8638. showToast('Removed', 'Area range removed', 'success');
  8639. loadDynamicRouting();
  8640. } catch (err) {
  8641. showToast('Error', err.message, 'error');
  8642. }
  8643. }
  8644. async function enableSelectedOspfAreaRange() {
  8645. const id = state.selectedOspfRow?.['area-ranges'];
  8646. if (!id) return;
  8647. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8648. if (!r) return;
  8649. r.disabled = false;
  8650. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8651. loadDynamicRouting();
  8652. }
  8653. async function disableSelectedOspfAreaRange() {
  8654. const id = state.selectedOspfRow?.['area-ranges'];
  8655. if (!id) return;
  8656. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8657. if (!r) return;
  8658. r.disabled = true;
  8659. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8660. loadDynamicRouting();
  8661. }
  8662. async function removeSelectedOspfAreaRange() {
  8663. const id = state.selectedOspfRow?.['area-ranges'];
  8664. if (!id) return;
  8665. if (!confirm('Delete selected area range?')) return;
  8666. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8667. loadDynamicRouting();
  8668. }
  8669. async function promptCommentOspfAreaRange() {
  8670. const id = state.selectedOspfRow?.['area-ranges'];
  8671. if (!id) return;
  8672. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8673. if (!r) return;
  8674. const comment = prompt('Enter comment for area range:', r.comment || '');
  8675. if (comment === null) return;
  8676. r.comment = comment;
  8677. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8678. loadDynamicRouting();
  8679. }
  8680. // --- 4. OSPF INTERFACE TEMPLATE ---
  8681. function switchOspfTemplateTab(tab) {
  8682. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8683. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8684. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8685. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8686. if (tab === 'general') {
  8687. if (tabGen) tabGen.classList.remove('hidden');
  8688. if (tabAuth) tabAuth.classList.add('hidden');
  8689. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8690. 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';
  8691. } else {
  8692. if (tabGen) tabGen.classList.add('hidden');
  8693. if (tabAuth) tabAuth.classList.remove('hidden');
  8694. 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';
  8695. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8696. }
  8697. }
  8698. function populateTemplateAreaDropdowns() {
  8699. const select = document.getElementById('modal-ospf-tmpl-area');
  8700. if (select) {
  8701. const cur = select.value;
  8702. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8703. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8704. if (cur) select.value = cur;
  8705. }
  8706. }
  8707. function openOspfTemplateModal(id = null) {
  8708. const isEdit = !!id;
  8709. populateTemplateAreaDropdowns();
  8710. switchOspfTemplateTab('general');
  8711. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8712. id: '',
  8713. interfaces: '',
  8714. area: 'Default',
  8715. networks: '',
  8716. network_type: 'broadcast',
  8717. cost: 1,
  8718. priority: 128,
  8719. passive: false,
  8720. hello_interval: 10,
  8721. dead_interval: 40,
  8722. auth: 'none',
  8723. auth_key: '',
  8724. disabled: false,
  8725. comment: ''
  8726. };
  8727. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8728. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8729. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8730. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8731. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8732. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8733. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8734. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8735. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8736. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8737. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8738. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8739. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8740. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8741. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8742. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8743. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8744. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8745. }
  8746. function openEditOspfTemplateModal(id) {
  8747. openOspfTemplateModal(id);
  8748. }
  8749. function closeOspfTemplateModal() {
  8750. document.getElementById('ospf-template-modal').classList.add('hidden');
  8751. }
  8752. async function submitOspfTemplate(e) {
  8753. if (e) e.preventDefault();
  8754. const payload = {
  8755. id: document.getElementById('modal-ospf-tmpl-id').value,
  8756. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8757. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8758. area: document.getElementById('modal-ospf-tmpl-area').value,
  8759. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8760. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8761. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8762. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8763. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8764. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8765. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8766. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8767. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8768. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8769. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8770. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8771. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8772. };
  8773. try {
  8774. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8775. method: 'POST',
  8776. headers: { 'Content-Type': 'application/json' },
  8777. body: JSON.stringify(payload)
  8778. });
  8779. if (res.ok) {
  8780. closeOspfTemplateModal();
  8781. showToast('Saved', 'Interface template saved', 'success');
  8782. loadDynamicRouting();
  8783. } else {
  8784. const err = await res.json();
  8785. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8786. }
  8787. } catch (err) {
  8788. showToast('Error', err.message, 'error');
  8789. }
  8790. }
  8791. function applyOspfTemplateForm() {
  8792. submitOspfTemplate(null);
  8793. }
  8794. function copyOspfTemplate() {
  8795. document.getElementById('modal-ospf-tmpl-id').value = '';
  8796. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8797. showToast('Copied', 'Duplicated as new template', 'info');
  8798. }
  8799. async function deleteCurrentOspfTemplate() {
  8800. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8801. if (!id) return;
  8802. if (!confirm('Delete this interface template?')) return;
  8803. try {
  8804. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8805. closeOspfTemplateModal();
  8806. showToast('Removed', 'Interface template deleted', 'success');
  8807. loadDynamicRouting();
  8808. } catch (err) {
  8809. showToast('Error', err.message, 'error');
  8810. }
  8811. }
  8812. async function enableSelectedOspfTemplate() {
  8813. const id = state.selectedOspfRow?.templates;
  8814. if (!id) return;
  8815. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8816. method: 'POST',
  8817. headers: { 'Content-Type': 'application/json' },
  8818. body: JSON.stringify({ disabled: false })
  8819. });
  8820. loadDynamicRouting();
  8821. }
  8822. async function disableSelectedOspfTemplate() {
  8823. const id = state.selectedOspfRow?.templates;
  8824. if (!id) return;
  8825. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8826. method: 'POST',
  8827. headers: { 'Content-Type': 'application/json' },
  8828. body: JSON.stringify({ disabled: true })
  8829. });
  8830. loadDynamicRouting();
  8831. }
  8832. async function removeSelectedOspfTemplate() {
  8833. const id = state.selectedOspfRow?.templates;
  8834. if (!id) return;
  8835. if (!confirm('Delete selected interface template?')) return;
  8836. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8837. loadDynamicRouting();
  8838. }
  8839. async function promptCommentOspfTemplate() {
  8840. const id = state.selectedOspfRow?.templates;
  8841. if (!id) return;
  8842. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8843. if (!tmpl) return;
  8844. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8845. if (comment === null) return;
  8846. tmpl.comment = comment;
  8847. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8848. method: 'POST',
  8849. headers: { 'Content-Type': 'application/json' },
  8850. body: JSON.stringify(tmpl)
  8851. });
  8852. loadDynamicRouting();
  8853. }
  8854. // --- 5. OSPF STATIC NEIGHBOR ---
  8855. function populateStaticNbrAreaDropdowns() {
  8856. const select = document.getElementById('modal-ospf-snbr-area');
  8857. if (select) {
  8858. const cur = select.value;
  8859. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8860. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8861. if (cur) select.value = cur;
  8862. }
  8863. }
  8864. function openOspfStaticNbrModal(id = null) {
  8865. const isEdit = !!id;
  8866. populateStaticNbrAreaDropdowns();
  8867. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8868. id: '',
  8869. address: '',
  8870. area: 'Default',
  8871. poll_interval: 120,
  8872. cost: 1,
  8873. disabled: false,
  8874. comment: ''
  8875. };
  8876. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8877. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8878. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8879. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8880. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8881. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8882. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8883. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8884. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8885. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8886. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8887. }
  8888. function openEditOspfStaticNbrModal(id) {
  8889. openOspfStaticNbrModal(id);
  8890. }
  8891. function closeOspfStaticNbrModal() {
  8892. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8893. }
  8894. async function submitOspfStaticNbr(e) {
  8895. if (e) e.preventDefault();
  8896. const payload = {
  8897. id: document.getElementById('modal-ospf-snbr-id').value,
  8898. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8899. area: document.getElementById('modal-ospf-snbr-area').value,
  8900. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8901. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8902. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8903. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8904. };
  8905. try {
  8906. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8907. method: 'POST',
  8908. headers: { 'Content-Type': 'application/json' },
  8909. body: JSON.stringify(payload)
  8910. });
  8911. if (res.ok) {
  8912. closeOspfStaticNbrModal();
  8913. showToast('Saved', 'Static neighbor saved', 'success');
  8914. loadDynamicRouting();
  8915. } else {
  8916. const err = await res.json();
  8917. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8918. }
  8919. } catch (err) {
  8920. showToast('Error', err.message, 'error');
  8921. }
  8922. }
  8923. function applyOspfStaticNbrForm() {
  8924. submitOspfStaticNbr(null);
  8925. }
  8926. async function deleteCurrentOspfStaticNbr() {
  8927. const id = document.getElementById('modal-ospf-snbr-id').value;
  8928. if (!id) return;
  8929. if (!confirm('Delete this static neighbor?')) return;
  8930. try {
  8931. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8932. closeOspfStaticNbrModal();
  8933. showToast('Removed', 'Static neighbor removed', 'success');
  8934. loadDynamicRouting();
  8935. } catch (err) {
  8936. showToast('Error', err.message, 'error');
  8937. }
  8938. }
  8939. async function enableSelectedOspfStaticNbr() {
  8940. const id = state.selectedOspfRow?.['static-nbrs'];
  8941. if (!id) return;
  8942. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8943. if (!n) return;
  8944. n.disabled = false;
  8945. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8946. loadDynamicRouting();
  8947. }
  8948. async function disableSelectedOspfStaticNbr() {
  8949. const id = state.selectedOspfRow?.['static-nbrs'];
  8950. if (!id) return;
  8951. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8952. if (!n) return;
  8953. n.disabled = true;
  8954. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8955. loadDynamicRouting();
  8956. }
  8957. async function removeSelectedOspfStaticNbr() {
  8958. const id = state.selectedOspfRow?.['static-nbrs'];
  8959. if (!id) return;
  8960. if (!confirm('Delete selected static neighbor?')) return;
  8961. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8962. loadDynamicRouting();
  8963. }
  8964. async function promptCommentOspfStaticNbr() {
  8965. const id = state.selectedOspfRow?.['static-nbrs'];
  8966. if (!id) return;
  8967. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8968. if (!n) return;
  8969. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8970. if (comment === null) return;
  8971. n.comment = comment;
  8972. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8973. loadDynamicRouting();
  8974. }
  8975. // Backward-compat aliases
  8976. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8977. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8978. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8979. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8980. function deleteOspfInterface(id) {
  8981. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8982. }
  8983. function toggleOspfInterfaceState(id, disabled) {
  8984. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8985. method: 'POST',
  8986. headers: { 'Content-Type': 'application/json' },
  8987. body: JSON.stringify({ disabled })
  8988. }).then(() => loadDynamicRouting());
  8989. }
  8990. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8991. function deleteOspfArea(id) {
  8992. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8993. }
  8994. // ============================================================================
  8995. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8996. // ============================================================================
  8997. function switchBridgeSubTab(tab) {
  8998. state.bridgeSubTab = tab;
  8999. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9000. tabs.forEach(t => {
  9001. const panel = document.getElementById(`bridge-subtab-${t}`);
  9002. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9003. if (panel) {
  9004. if (t === tab) panel.classList.remove('hidden');
  9005. else panel.classList.add('hidden');
  9006. }
  9007. if (btn) {
  9008. if (t === tab) {
  9009. 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';
  9010. } else {
  9011. 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';
  9012. }
  9013. }
  9014. });
  9015. const addBtn = document.getElementById('bridge-top-action-btn');
  9016. if (addBtn) {
  9017. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9018. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9019. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9020. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9021. }
  9022. if (tab === 'hosts') loadBridgeHosts();
  9023. setTimeout(initTableSorting, 50);
  9024. }
  9025. function openCurrentBridgeModal() {
  9026. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9027. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9028. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9029. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9030. }
  9031. async function loadBridge() {
  9032. try {
  9033. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9034. fetch(`${API_BASE}/bridge/bridges`),
  9035. fetch(`${API_BASE}/bridge/ports`),
  9036. fetch(`${API_BASE}/bridge/vlans`),
  9037. fetch(`${API_BASE}/bridge/summary`),
  9038. fetch(`${API_BASE}/vpn/eoip`),
  9039. fetch(`${API_BASE}/vlans`)
  9040. ]);
  9041. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9042. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9043. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9044. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9045. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9046. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9047. // Badges & Stats
  9048. const bBridges = document.getElementById('bridge-badge-bridges');
  9049. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9050. const bPorts = document.getElementById('bridge-badge-ports');
  9051. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9052. const bVlans = document.getElementById('bridge-badge-vlans');
  9053. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9054. const bHosts = document.getElementById('bridge-badge-hosts');
  9055. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9056. const sBr = document.getElementById('bridge-stat-bridges');
  9057. if (sBr) sBr.innerText = (state.bridges || []).length;
  9058. const sPorts = document.getElementById('bridge-stat-ports');
  9059. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9060. const sHosts = document.getElementById('bridge-stat-hosts');
  9061. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9062. renderBridges();
  9063. renderBridgePorts();
  9064. renderBridgeVLANs();
  9065. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9066. } catch (err) {
  9067. console.error('Failed to load bridge subsystem:', err);
  9068. }
  9069. }
  9070. // ----------------- Bridges -----------------
  9071. function renderBridges() {
  9072. const tbody = document.getElementById('bridge-table-body');
  9073. const empty = document.getElementById('bridge-empty-bridges');
  9074. const countBadge = document.getElementById('bridge-count-badge');
  9075. if (!tbody) return;
  9076. tbody.innerHTML = '';
  9077. const bridges = state.bridges || [];
  9078. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9079. if (bridges.length === 0) {
  9080. empty?.classList.remove('hidden');
  9081. return;
  9082. }
  9083. empty?.classList.add('hidden');
  9084. bridges.forEach((b, idx) => {
  9085. const tr = document.createElement('tr');
  9086. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9087. // Format IP addresses pill list
  9088. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9089. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9090. ipsHtml = b.ip_addresses.map(ip => `
  9091. <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">
  9092. <span>${ip}</span>
  9093. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9094. </span>
  9095. `).join(' ');
  9096. }
  9097. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9098. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9099. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9100. tr.innerHTML = `
  9101. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9102. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9103. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9104. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9105. </td>
  9106. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9107. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9108. <td class="py-2.5 px-3">
  9109. <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>
  9110. </td>
  9111. <td class="py-2.5 px-3 text-center">
  9112. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9113. </td>
  9114. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9115. <td class="py-2.5 px-3">
  9116. <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>
  9117. </td>
  9118. <td class="py-2.5 px-3">
  9119. <div class="flex items-center gap-1.5 flex-wrap">
  9120. ${ipsHtml}
  9121. <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>
  9122. </div>
  9123. </td>
  9124. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9125. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9126. </td>
  9127. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9128. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9129. <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>
  9130. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9131. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9132. </td>
  9133. `;
  9134. tbody.appendChild(tr);
  9135. });
  9136. }
  9137. function openAddBridgeModal() {
  9138. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9139. document.getElementById('bridge-modal-id').value = '';
  9140. document.getElementById('bridge-modal-name').value = 'bridge1';
  9141. document.getElementById('bridge-modal-name').disabled = false;
  9142. document.getElementById('bridge-modal-mtu').value = '1500';
  9143. document.getElementById('bridge-modal-mac').value = '';
  9144. document.getElementById('bridge-modal-stp').value = 'rstp';
  9145. document.getElementById('bridge-modal-priority').value = '32768';
  9146. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9147. document.getElementById('bridge-modal-pvid').value = '1';
  9148. document.getElementById('bridge-modal-fastforward').checked = true;
  9149. document.getElementById('bridge-modal-comment').value = '';
  9150. document.getElementById('bridge-modal-disabled').checked = false;
  9151. toggleBridgeModalVlanFiltering();
  9152. document.getElementById('bridge-modal').classList.remove('hidden');
  9153. }
  9154. function openEditBridgeModal(id) {
  9155. const b = (state.bridges || []).find(x => x.id === id);
  9156. if (!b) return;
  9157. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9158. document.getElementById('bridge-modal-id').value = b.id;
  9159. document.getElementById('bridge-modal-name').value = b.name;
  9160. document.getElementById('bridge-modal-name').disabled = true;
  9161. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9162. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9163. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9164. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9165. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9166. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9167. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9168. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9169. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9170. toggleBridgeModalVlanFiltering();
  9171. document.getElementById('bridge-modal').classList.remove('hidden');
  9172. }
  9173. function closeBridgeModal() {
  9174. document.getElementById('bridge-modal').classList.add('hidden');
  9175. }
  9176. function toggleBridgeModalVlanFiltering() {
  9177. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9178. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9179. if (pvidBox) {
  9180. if (chk) pvidBox.classList.remove('opacity-40');
  9181. else pvidBox.classList.add('opacity-40');
  9182. }
  9183. }
  9184. async function submitSaveBridge(e) {
  9185. e.preventDefault();
  9186. const id = document.getElementById('bridge-modal-id').value;
  9187. const name = document.getElementById('bridge-modal-name').value.trim();
  9188. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9189. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9190. const stp = document.getElementById('bridge-modal-stp').value;
  9191. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9192. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9193. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9194. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9195. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9196. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9197. try {
  9198. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9199. method: 'POST',
  9200. headers: { 'Content-Type': 'application/json' },
  9201. body: JSON.stringify({
  9202. id,
  9203. name,
  9204. mtu,
  9205. mac_address: mac,
  9206. stp,
  9207. priority,
  9208. vlan_filtering: vlanFiltering,
  9209. pvid,
  9210. fast_forward: fastForward,
  9211. comment,
  9212. disabled
  9213. })
  9214. });
  9215. if (res.ok) {
  9216. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9217. closeBridgeModal();
  9218. loadBridge();
  9219. fetchData(false);
  9220. } else {
  9221. const err = await res.json();
  9222. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9223. }
  9224. } catch (err) {
  9225. showToast('Error', err.message, 'error');
  9226. }
  9227. }
  9228. async function toggleBridgeState(id, disabled) {
  9229. try {
  9230. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9231. method: 'POST',
  9232. headers: { 'Content-Type': 'application/json' },
  9233. body: JSON.stringify({ disabled })
  9234. });
  9235. if (res.ok) {
  9236. loadBridge();
  9237. fetchData(false);
  9238. }
  9239. } catch (err) {
  9240. showToast('Error', err.message, 'error');
  9241. }
  9242. }
  9243. async function deleteBridge(id) {
  9244. const b = (state.bridges || []).find(x => x.id === id);
  9245. const name = b ? b.name : id;
  9246. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9247. try {
  9248. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9249. if (res.ok) {
  9250. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9251. loadBridge();
  9252. fetchData(false);
  9253. } else {
  9254. const err = await res.json();
  9255. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9256. }
  9257. } catch (err) {
  9258. showToast('Error', err.message, 'error');
  9259. }
  9260. }
  9261. // ----------------- Bridge IP Assignments -----------------
  9262. function openAddBridgeIPModal(id, name) {
  9263. document.getElementById('bridge-ip-modal-id').value = id;
  9264. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9265. document.getElementById('bridge-ip-modal-cidr').value = '';
  9266. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9267. }
  9268. function closeBridgeIPModal() {
  9269. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9270. }
  9271. async function submitAddBridgeIP(e) {
  9272. e.preventDefault();
  9273. const id = document.getElementById('bridge-ip-modal-id').value;
  9274. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9275. try {
  9276. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9277. method: 'POST',
  9278. headers: { 'Content-Type': 'application/json' },
  9279. body: JSON.stringify({ ip })
  9280. });
  9281. if (res.ok) {
  9282. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9283. closeBridgeIPModal();
  9284. loadBridge();
  9285. fetchData(false);
  9286. } else {
  9287. const err = await res.json();
  9288. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9289. }
  9290. } catch (err) {
  9291. showToast('Error', err.message, 'error');
  9292. }
  9293. }
  9294. async function deleteBridgeIP(id, ip) {
  9295. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9296. try {
  9297. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9298. method: 'DELETE',
  9299. headers: { 'Content-Type': 'application/json' },
  9300. body: JSON.stringify({ ip })
  9301. });
  9302. if (res.ok) {
  9303. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9304. loadBridge();
  9305. fetchData(false);
  9306. }
  9307. } catch (err) {
  9308. showToast('Error', err.message, 'error');
  9309. }
  9310. }
  9311. // ----------------- Bridge Ports -----------------
  9312. function renderBridgePorts() {
  9313. const tbody = document.getElementById('bridge-ports-table-body');
  9314. const empty = document.getElementById('bridge-empty-ports');
  9315. const countBadge = document.getElementById('bridge-ports-count-badge');
  9316. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9317. if (!tbody) return;
  9318. tbody.innerHTML = '';
  9319. // Update filter select
  9320. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9321. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9322. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9323. if (ports.length === 0) {
  9324. empty?.classList.remove('hidden');
  9325. return;
  9326. }
  9327. empty?.classList.add('hidden');
  9328. ports.forEach((p, idx) => {
  9329. const tr = document.createElement('tr');
  9330. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9331. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9332. tr.innerHTML = `
  9333. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9334. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9335. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9336. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9337. </td>
  9338. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9339. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9340. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9341. <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>
  9342. <td class="py-2.5 px-3">
  9343. ${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>'}
  9344. </td>
  9345. <td class="py-2.5 px-3">
  9346. <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>
  9347. </td>
  9348. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9349. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9350. <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>
  9351. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9352. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9353. </td>
  9354. `;
  9355. tbody.appendChild(tr);
  9356. });
  9357. }
  9358. function openAddBridgePortModal() {
  9359. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9360. document.getElementById('bridge-port-modal-id').value = '';
  9361. populateBridgeSelect('bridge-port-modal-bridge');
  9362. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9363. document.getElementById('bridge-port-modal-pvid').value = '1';
  9364. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9365. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9366. document.getElementById('bridge-port-modal-horizon').value = '0';
  9367. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9368. document.getElementById('bridge-port-modal-priority').value = '128';
  9369. document.getElementById('bridge-port-modal-learn').checked = true;
  9370. document.getElementById('bridge-port-modal-comment').value = '';
  9371. document.getElementById('bridge-port-modal-disabled').checked = false;
  9372. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9373. }
  9374. function openEditBridgePortModal(id) {
  9375. const p = (state.bridgePorts || []).find(x => x.id === id);
  9376. if (!p) return;
  9377. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9378. document.getElementById('bridge-port-modal-id').value = p.id;
  9379. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9380. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9381. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9382. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9383. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9384. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9385. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9386. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9387. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9388. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9389. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9390. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9391. }
  9392. function closeBridgePortModal() {
  9393. document.getElementById('bridge-port-modal').classList.add('hidden');
  9394. }
  9395. async function submitSaveBridgePort(e) {
  9396. e.preventDefault();
  9397. const id = document.getElementById('bridge-port-modal-id').value;
  9398. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9399. const iface = document.getElementById('bridge-port-modal-interface').value;
  9400. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9401. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9402. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9403. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9404. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9405. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9406. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9407. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9408. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9409. try {
  9410. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9411. method: 'POST',
  9412. headers: { 'Content-Type': 'application/json' },
  9413. body: JSON.stringify({
  9414. id,
  9415. bridge,
  9416. interface: iface,
  9417. pvid,
  9418. frame_types: frameTypes,
  9419. ingress_filtering: ingressFiltering,
  9420. horizon,
  9421. path_cost: pathCost,
  9422. priority,
  9423. learn,
  9424. comment,
  9425. disabled
  9426. })
  9427. });
  9428. if (res.ok) {
  9429. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9430. closeBridgePortModal();
  9431. loadBridge();
  9432. fetchData(false);
  9433. } else {
  9434. const err = await res.json();
  9435. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9436. }
  9437. } catch (err) {
  9438. showToast('Error', err.message, 'error');
  9439. }
  9440. }
  9441. async function toggleBridgePortState(id, disabled) {
  9442. try {
  9443. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9444. method: 'POST',
  9445. headers: { 'Content-Type': 'application/json' },
  9446. body: JSON.stringify({ disabled })
  9447. });
  9448. if (res.ok) {
  9449. loadBridge();
  9450. fetchData(false);
  9451. }
  9452. } catch (err) {
  9453. showToast('Error', err.message, 'error');
  9454. }
  9455. }
  9456. async function deleteBridgePort(id) {
  9457. const p = (state.bridgePorts || []).find(x => x.id === id);
  9458. const iface = p ? p.interface : id;
  9459. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9460. try {
  9461. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9462. if (res.ok) {
  9463. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9464. loadBridge();
  9465. fetchData(false);
  9466. }
  9467. } catch (err) {
  9468. showToast('Error', err.message, 'error');
  9469. }
  9470. }
  9471. // ----------------- Bridge VLANs -----------------
  9472. function renderBridgeVLANs() {
  9473. const tbody = document.getElementById('bridge-vlans-table-body');
  9474. const empty = document.getElementById('bridge-empty-vlans');
  9475. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9476. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9477. if (!tbody) return;
  9478. tbody.innerHTML = '';
  9479. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9480. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9481. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9482. if (vlans.length === 0) {
  9483. empty?.classList.remove('hidden');
  9484. return;
  9485. }
  9486. empty?.classList.add('hidden');
  9487. vlans.forEach((v, idx) => {
  9488. const tr = document.createElement('tr');
  9489. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9490. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9491. ? 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(' ')
  9492. : '<span class="text-slate-600">none</span>';
  9493. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9494. ? 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(' ')
  9495. : '<span class="text-slate-600">none</span>';
  9496. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9497. tr.innerHTML = `
  9498. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9499. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9500. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9501. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9502. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9503. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9504. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9505. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9506. <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>
  9507. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9508. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9509. </td>
  9510. `;
  9511. tbody.appendChild(tr);
  9512. });
  9513. }
  9514. function openAddBridgeVLANModal() {
  9515. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9516. document.getElementById('bridge-vlan-modal-id').value = '';
  9517. populateBridgeSelect('bridge-vlan-modal-bridge');
  9518. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9519. document.getElementById('bridge-vlan-modal-comment').value = '';
  9520. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9521. updateBridgeVlanPortCheckboxes();
  9522. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9523. }
  9524. function openEditBridgeVLANModal(id) {
  9525. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9526. if (!v) return;
  9527. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9528. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9529. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9530. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9531. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9532. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9533. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9534. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9535. }
  9536. function closeBridgeVlanModal() {
  9537. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9538. }
  9539. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9540. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9541. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9542. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9543. if (!taggedBox || !untaggedBox) return;
  9544. // Ports belonging to the selected bridge
  9545. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9546. if (memberPorts.length === 0) {
  9547. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9548. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9549. return;
  9550. }
  9551. taggedBox.innerHTML = memberPorts.map(p => `
  9552. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9553. <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">
  9554. <span>${p.interface}</span>
  9555. </label>
  9556. `).join('');
  9557. untaggedBox.innerHTML = memberPorts.map(p => `
  9558. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9559. <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">
  9560. <span>${p.interface}</span>
  9561. </label>
  9562. `).join('');
  9563. }
  9564. async function submitSaveBridgeVLAN(e) {
  9565. e.preventDefault();
  9566. const id = document.getElementById('bridge-vlan-modal-id').value;
  9567. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9568. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9569. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9570. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9571. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9572. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9573. try {
  9574. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9575. method: 'POST',
  9576. headers: { 'Content-Type': 'application/json' },
  9577. body: JSON.stringify({
  9578. id,
  9579. bridge,
  9580. vlan_ids: vlanIDs,
  9581. tagged,
  9582. untagged,
  9583. comment,
  9584. disabled
  9585. })
  9586. });
  9587. if (res.ok) {
  9588. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9589. closeBridgeVlanModal();
  9590. loadBridge();
  9591. } else {
  9592. const err = await res.json();
  9593. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9594. }
  9595. } catch (err) {
  9596. showToast('Error', err.message, 'error');
  9597. }
  9598. }
  9599. async function toggleBridgeVLANState(id, disabled) {
  9600. try {
  9601. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9602. method: 'POST',
  9603. headers: { 'Content-Type': 'application/json' },
  9604. body: JSON.stringify({ disabled })
  9605. });
  9606. if (res.ok) loadBridge();
  9607. } catch (err) {
  9608. showToast('Error', err.message, 'error');
  9609. }
  9610. }
  9611. async function deleteBridgeVLAN(id) {
  9612. if (!confirm('Delete this bridge VLAN entry?')) return;
  9613. try {
  9614. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9615. if (res.ok) {
  9616. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9617. loadBridge();
  9618. }
  9619. } catch (err) {
  9620. showToast('Error', err.message, 'error');
  9621. }
  9622. }
  9623. // ----------------- Hosts / MAC Table -----------------
  9624. async function loadBridgeHosts() {
  9625. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9626. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9627. try {
  9628. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9629. const res = await fetch(url);
  9630. if (res.ok) {
  9631. state.bridgeHosts = await res.json();
  9632. renderBridgeHosts();
  9633. }
  9634. } catch (err) {
  9635. console.error('Failed to load bridge hosts:', err);
  9636. }
  9637. }
  9638. function renderBridgeHosts() {
  9639. const tbody = document.getElementById('bridge-hosts-table-body');
  9640. const empty = document.getElementById('bridge-empty-hosts');
  9641. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9642. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9643. if (!tbody) return;
  9644. tbody.innerHTML = '';
  9645. const hosts = (state.bridgeHosts || []).filter(h => {
  9646. if (!search) return true;
  9647. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9648. });
  9649. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9650. if (hosts.length === 0) {
  9651. empty?.classList.remove('hidden');
  9652. return;
  9653. }
  9654. empty?.classList.add('hidden');
  9655. hosts.forEach(h => {
  9656. const tr = document.createElement('tr');
  9657. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9658. let flagBadges = '';
  9659. 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>';
  9660. 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>';
  9661. 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>';
  9662. tr.innerHTML = `
  9663. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9664. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9665. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9666. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9667. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9668. <td class="py-2.5 px-3">${flagBadges}</td>
  9669. `;
  9670. tbody.appendChild(tr);
  9671. });
  9672. }
  9673. async function flushBridgeHosts() {
  9674. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9675. if (!selBridge) {
  9676. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9677. return;
  9678. }
  9679. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9680. try {
  9681. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9682. method: 'POST',
  9683. headers: { 'Content-Type': 'application/json' },
  9684. body: JSON.stringify({ bridge: selBridge })
  9685. });
  9686. if (res.ok) {
  9687. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9688. loadBridgeHosts();
  9689. }
  9690. } catch (err) {
  9691. showToast('Error', err.message, 'error');
  9692. }
  9693. }
  9694. // ----------------- Helpers -----------------
  9695. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9696. const sel = document.getElementById(selectId);
  9697. if (!sel) return;
  9698. const prevVal = currentVal || sel.value;
  9699. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9700. (state.bridges || []).forEach(b => {
  9701. const opt = document.createElement('option');
  9702. opt.value = b.name;
  9703. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9704. if (b.name === prevVal) opt.selected = true;
  9705. sel.appendChild(opt);
  9706. });
  9707. }
  9708. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9709. const sel = document.getElementById(selectId);
  9710. if (!sel) return;
  9711. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9712. // 1. Physical Interfaces
  9713. const grpPhys = document.createElement('optgroup');
  9714. grpPhys.label = 'Physical Interfaces';
  9715. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9716. const opt = document.createElement('option');
  9717. opt.value = i.name;
  9718. opt.innerText = `${i.name} (${i.role || i.type})`;
  9719. if (i.name === currentVal) opt.selected = true;
  9720. grpPhys.appendChild(opt);
  9721. });
  9722. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9723. // 2. VLAN Sub-interfaces
  9724. const grpVlans = document.createElement('optgroup');
  9725. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9726. (state.vlans || []).forEach(v => {
  9727. const opt = document.createElement('option');
  9728. opt.value = v.name;
  9729. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9730. if (v.name === currentVal) opt.selected = true;
  9731. grpVlans.appendChild(opt);
  9732. });
  9733. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9734. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9735. const grpEoip = document.createElement('optgroup');
  9736. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9737. (state.eoipTunnels || []).forEach(t => {
  9738. const opt = document.createElement('option');
  9739. opt.value = t.name;
  9740. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9741. if (t.name === currentVal) opt.selected = true;
  9742. grpEoip.appendChild(opt);
  9743. });
  9744. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9745. }
  9746. // -------------------------------------------------------------
  9747. // RouterOS v7 Routing Filters Management (/routing filter)
  9748. // -------------------------------------------------------------
  9749. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9750. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9751. if (!state.rfSort) state.rfSort = {};
  9752. function switchRoutingFilterTab(tab) {
  9753. state.activeRoutingFilterTab = tab;
  9754. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9755. tabs.forEach(t => {
  9756. const btn = document.getElementById(`tab-rf-${t}`);
  9757. const content = document.getElementById(`tab-content-rf-${t}`);
  9758. if (btn) {
  9759. if (t === tab) {
  9760. 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';
  9761. } else {
  9762. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9763. }
  9764. }
  9765. if (content) {
  9766. if (t === tab) content.classList.remove('hidden');
  9767. else content.classList.add('hidden');
  9768. }
  9769. });
  9770. const chainContainer = document.getElementById('rf-chain-filter-container');
  9771. if (chainContainer) {
  9772. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9773. else chainContainer.classList.add('hidden');
  9774. }
  9775. renderRoutingFilters();
  9776. }
  9777. function selectFilterRow(tab, id) {
  9778. if (state.selectedFilterRow[tab] === id) {
  9779. delete state.selectedFilterRow[tab];
  9780. } else {
  9781. state.selectedFilterRow[tab] = id;
  9782. }
  9783. if (tab === 'rules') renderRoutingFilterRules();
  9784. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9785. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9786. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9787. }
  9788. function openRoutingFilterNewModal() {
  9789. const tab = state.activeRoutingFilterTab || 'rules';
  9790. if (tab === 'rules') openAddRoutingFilterModal();
  9791. else if (tab === 'select-rules') openAddSelectRuleModal();
  9792. else if (tab === 'community-lists') openAddCommunityListModal();
  9793. else if (tab === 'as-lists') openAddASListModal();
  9794. }
  9795. function toggleSelectedRoutingFilter(disabled) {
  9796. const tab = state.activeRoutingFilterTab || 'rules';
  9797. const id = state.selectedFilterRow[tab];
  9798. if (!id) {
  9799. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9800. return;
  9801. }
  9802. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9803. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9804. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9805. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9806. }
  9807. function removeSelectedRoutingFilter() {
  9808. const tab = state.activeRoutingFilterTab || 'rules';
  9809. const id = state.selectedFilterRow[tab];
  9810. if (!id) {
  9811. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9812. return;
  9813. }
  9814. if (tab === 'rules') deleteRoutingFilter(id);
  9815. else if (tab === 'select-rules') deleteSelectRule(id);
  9816. else if (tab === 'community-lists') deleteCommunityList(id);
  9817. else if (tab === 'as-lists') deleteASList(id);
  9818. }
  9819. function searchRoutingFilters(q) {
  9820. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9821. renderRoutingFilters();
  9822. }
  9823. function sortFilterTable(tab, col) {
  9824. if (!state.rfSort) state.rfSort = {};
  9825. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9826. if (state.rfSort[tab].col === col) {
  9827. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9828. } else {
  9829. state.rfSort[tab].col = col;
  9830. state.rfSort[tab].asc = true;
  9831. }
  9832. const asc = state.rfSort[tab].asc;
  9833. let list = [];
  9834. if (tab === 'rules') list = state.routingFilters || [];
  9835. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9836. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9837. else if (tab === 'as-lists') list = state.routingASLists || [];
  9838. list.sort((a, b) => {
  9839. let valA = a[col] ?? '';
  9840. let valB = b[col] ?? '';
  9841. if (col === 'flags') {
  9842. valA = a.disabled ? 'X' : 'A';
  9843. valB = b.disabled ? 'X' : 'A';
  9844. }
  9845. if (typeof valA === 'number' && typeof valB === 'number') {
  9846. return asc ? valA - valB : valB - valA;
  9847. }
  9848. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9849. });
  9850. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9851. allCols.forEach(c => {
  9852. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9853. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9854. });
  9855. if (tab === 'rules') renderRoutingFilterRules();
  9856. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9857. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9858. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9859. }
  9860. function renderRoutingFilters() {
  9861. const navBadge = document.getElementById('badge-filters-count');
  9862. const allRules = state.routingFilters || [];
  9863. if (navBadge) navBadge.innerText = allRules.length;
  9864. // Populate chain filter select options and datalist
  9865. const chainSelect = document.getElementById('routing-filter-chain-select');
  9866. const chainDatalist = document.getElementById('dl-routing-chains');
  9867. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9868. if (chainSelect) {
  9869. const currentVal = state.filterChainSelected || 'all';
  9870. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9871. uniqueChains.map(ch => {
  9872. const count = allRules.filter(r => r.chain === ch).length;
  9873. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9874. }).join('');
  9875. chainSelect.value = currentVal;
  9876. }
  9877. if (chainDatalist) {
  9878. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9879. }
  9880. renderRoutingFilterRules();
  9881. renderRoutingFilterSelectRules();
  9882. renderRoutingFilterCommunityLists();
  9883. renderRoutingFilterASLists();
  9884. }
  9885. function filterRoutingFiltersByChain(chain) {
  9886. state.filterChainSelected = chain;
  9887. renderRoutingFilters();
  9888. }
  9889. // -------------------------------------------------------------
  9890. // TAB 1: RULES (/routing filter rule)
  9891. // -------------------------------------------------------------
  9892. function renderRoutingFilterRules() {
  9893. const tbody = document.getElementById('routing-filter-rules-tbody');
  9894. if (!tbody) return;
  9895. const empty = document.getElementById('rf-rules-empty');
  9896. const statusCount = document.getElementById('rf-status-count');
  9897. let list = (state.routingFilters || []).slice();
  9898. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9899. list = list.filter(r => r.chain === state.filterChainSelected);
  9900. }
  9901. const q = state.rfSearchQuery;
  9902. if (q) {
  9903. list = list.filter(r =>
  9904. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9905. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9906. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9907. (r.comment && r.comment.toLowerCase().includes(q))
  9908. );
  9909. }
  9910. if (!state.rfSort?.['rules']) {
  9911. list.sort((a, b) => {
  9912. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9913. return (a.rule_order || 0) - (b.rule_order || 0);
  9914. });
  9915. }
  9916. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9917. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9918. }
  9919. if (list.length === 0) {
  9920. tbody.innerHTML = '';
  9921. if (empty) empty.classList.remove('hidden');
  9922. return;
  9923. }
  9924. if (empty) empty.classList.add('hidden');
  9925. tbody.innerHTML = list.map(r => {
  9926. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9927. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9928. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9929. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9930. let ruleDisplay = '';
  9931. if (r.rule && r.rule.trim() !== '') {
  9932. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9933. } else {
  9934. let conds = [];
  9935. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9936. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9937. let act = r.action || 'accept';
  9938. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9939. }
  9940. return `
  9941. <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'}">
  9942. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9943. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9944. <td class="py-2 px-3">
  9945. <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>
  9946. </td>
  9947. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9948. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9949. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9950. <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>
  9951. <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>
  9952. <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'}">
  9953. ${r.disabled ? 'Enable' : 'Disable'}
  9954. </button>
  9955. <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">
  9956. Edit
  9957. </button>
  9958. <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">
  9959. ✕
  9960. </button>
  9961. </td>
  9962. </tr>
  9963. `;
  9964. }).join('');
  9965. }
  9966. // -------------------------------------------------------------
  9967. // TAB 2: SELECT RULES (/routing filter select-rule)
  9968. // -------------------------------------------------------------
  9969. function renderRoutingFilterSelectRules() {
  9970. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9971. if (!tbody) return;
  9972. const empty = document.getElementById('rf-select-rules-empty');
  9973. const statusCount = document.getElementById('rf-status-count');
  9974. let list = (state.routingSelectRules || []).slice();
  9975. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9976. list = list.filter(r => r.chain === state.filterChainSelected);
  9977. }
  9978. const q = state.rfSearchQuery;
  9979. if (q) {
  9980. list = list.filter(r =>
  9981. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9982. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9983. (r.comment && r.comment.toLowerCase().includes(q))
  9984. );
  9985. }
  9986. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9987. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9988. }
  9989. if (list.length === 0) {
  9990. tbody.innerHTML = '';
  9991. if (empty) empty.classList.remove('hidden');
  9992. return;
  9993. }
  9994. if (empty) empty.classList.add('hidden');
  9995. tbody.innerHTML = list.map(r => {
  9996. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9997. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9998. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9999. return `
  10000. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10001. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10002. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10003. <td class="py-2 px-3">
  10004. <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>
  10005. </td>
  10006. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10007. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10008. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10009. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10010. ${r.disabled ? 'Enable' : 'Disable'}
  10011. </button>
  10012. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10013. Edit
  10014. </button>
  10015. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10016. ✕
  10017. </button>
  10018. </td>
  10019. </tr>
  10020. `;
  10021. }).join('');
  10022. }
  10023. // -------------------------------------------------------------
  10024. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10025. // -------------------------------------------------------------
  10026. function renderRoutingFilterCommunityLists() {
  10027. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10028. if (!tbody) return;
  10029. const empty = document.getElementById('rf-comm-lists-empty');
  10030. const statusCount = document.getElementById('rf-status-count');
  10031. let list = (state.routingCommunityLists || []).slice();
  10032. const q = state.rfSearchQuery;
  10033. if (q) {
  10034. list = list.filter(cl =>
  10035. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10036. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10037. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10038. );
  10039. }
  10040. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10041. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10042. }
  10043. if (list.length === 0) {
  10044. tbody.innerHTML = '';
  10045. if (empty) empty.classList.remove('hidden');
  10046. return;
  10047. }
  10048. if (empty) empty.classList.add('hidden');
  10049. tbody.innerHTML = list.map(cl => {
  10050. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10051. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10052. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10053. const commBadges = (cl.communities || []).map(c =>
  10054. `<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>`
  10055. ).join(' ');
  10056. return `
  10057. <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'}">
  10058. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10059. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10060. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10061. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10062. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10063. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10064. <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'}">
  10065. ${cl.disabled ? 'Enable' : 'Disable'}
  10066. </button>
  10067. <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">
  10068. Edit
  10069. </button>
  10070. <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">
  10071. ✕
  10072. </button>
  10073. </td>
  10074. </tr>
  10075. `;
  10076. }).join('');
  10077. }
  10078. // -------------------------------------------------------------
  10079. // TAB 4: AS LISTS (/routing filter num-list)
  10080. // -------------------------------------------------------------
  10081. function renderRoutingFilterASLists() {
  10082. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10083. if (!tbody) return;
  10084. const empty = document.getElementById('rf-as-lists-empty');
  10085. const statusCount = document.getElementById('rf-status-count');
  10086. let list = (state.routingASLists || []).slice();
  10087. const q = state.rfSearchQuery;
  10088. if (q) {
  10089. list = list.filter(al =>
  10090. (al.name && al.name.toLowerCase().includes(q)) ||
  10091. (al.range && al.range.toLowerCase().includes(q)) ||
  10092. (al.comment && al.comment.toLowerCase().includes(q))
  10093. );
  10094. }
  10095. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10096. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10097. }
  10098. if (list.length === 0) {
  10099. tbody.innerHTML = '';
  10100. if (empty) empty.classList.remove('hidden');
  10101. return;
  10102. }
  10103. if (empty) empty.classList.add('hidden');
  10104. tbody.innerHTML = list.map(al => {
  10105. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10106. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10107. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10108. return `
  10109. <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'}">
  10110. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10111. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10112. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10113. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10114. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10115. <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'}">
  10116. ${al.disabled ? 'Enable' : 'Disable'}
  10117. </button>
  10118. <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">
  10119. Edit
  10120. </button>
  10121. <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">
  10122. ✕
  10123. </button>
  10124. </td>
  10125. </tr>
  10126. `;
  10127. }).join('');
  10128. }
  10129. // -------------------------------------------------------------
  10130. // SNIPPETS & WIZARD HELPERS
  10131. // -------------------------------------------------------------
  10132. function insertRuleSnippet(type) {
  10133. const textarea = document.getElementById('modal-rf-rule');
  10134. if (!textarea) return;
  10135. let snippet = '';
  10136. switch (type) {
  10137. case 'accept-default':
  10138. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10139. break;
  10140. case 'drop-rfc1918':
  10141. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10142. break;
  10143. case 'len-24':
  10144. snippet = 'if (dst-len > 24) { reject; }';
  10145. break;
  10146. case 'local-pref-150':
  10147. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10148. break;
  10149. case 'as-prepend-2':
  10150. snippet = 'set bgp-path-prepend 2; accept;';
  10151. break;
  10152. case 'set-comm':
  10153. snippet = 'set bgp-communities.add 65000:100; accept;';
  10154. break;
  10155. case 'match-comm':
  10156. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10157. break;
  10158. case 'reject-all':
  10159. snippet = 'reject;';
  10160. break;
  10161. }
  10162. if (!snippet) return;
  10163. if (!textarea.value.trim()) {
  10164. textarea.value = snippet;
  10165. } else {
  10166. textarea.value = textarea.value.trim() + '\n' + snippet;
  10167. }
  10168. }
  10169. function generateScriptFromWizard() {
  10170. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10171. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10172. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10173. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10174. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10175. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10176. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10177. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10178. const conds = [];
  10179. if (pfx) {
  10180. if (pfxLen) {
  10181. if (pfxLen.includes('-')) {
  10182. const parts = pfxLen.split('-');
  10183. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10184. } else {
  10185. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10186. }
  10187. } else {
  10188. conds.push(`dst in ${pfx}`);
  10189. }
  10190. }
  10191. if (proto && proto !== 'any') {
  10192. conds.push(`protocol ${proto}`);
  10193. }
  10194. if (asp) {
  10195. conds.push(`bgp-as-path "${asp}"`);
  10196. }
  10197. if (comm) {
  10198. conds.push(`bgp-communities includes ${comm}`);
  10199. }
  10200. const actions = [];
  10201. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10202. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10203. actions.push(`${act};`);
  10204. let code = '';
  10205. if (conds.length > 0) {
  10206. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10207. } else {
  10208. code = actions.join(' ');
  10209. }
  10210. const textarea = document.getElementById('modal-rf-rule');
  10211. if (textarea) textarea.value = code;
  10212. }
  10213. // -------------------------------------------------------------
  10214. // MODAL CRUD: RULES (/routing filter rule)
  10215. // -------------------------------------------------------------
  10216. function openAddRoutingFilterModal(defaultChain = '') {
  10217. const form = document.getElementById('routing-filter-form');
  10218. if (form) form.reset();
  10219. const idEl = document.getElementById('modal-rf-id');
  10220. if (idEl) idEl.value = '';
  10221. const titleEl = document.getElementById('modal-rf-title');
  10222. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10223. const chainEl = document.getElementById('modal-rf-chain');
  10224. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10225. const orderEl = document.getElementById('modal-rf-order');
  10226. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10227. const ruleEl = document.getElementById('modal-rf-rule');
  10228. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10229. const disEl = document.getElementById('modal-rf-disabled');
  10230. if (disEl) disEl.checked = false;
  10231. const modal = document.getElementById('modal-routing-filter');
  10232. if (modal) modal.classList.remove('hidden');
  10233. }
  10234. function openEditRoutingFilterModal(id) {
  10235. const r = (state.routingFilters || []).find(item => item.id === id);
  10236. if (!r) return;
  10237. const idEl = document.getElementById('modal-rf-id');
  10238. if (idEl) idEl.value = r.id;
  10239. const titleEl = document.getElementById('modal-rf-title');
  10240. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10241. const chainEl = document.getElementById('modal-rf-chain');
  10242. if (chainEl) chainEl.value = r.chain || '';
  10243. const orderEl = document.getElementById('modal-rf-order');
  10244. if (orderEl) orderEl.value = r.rule_order || 10;
  10245. const ruleEl = document.getElementById('modal-rf-rule');
  10246. if (ruleEl) {
  10247. if (r.rule) {
  10248. ruleEl.value = r.rule;
  10249. } else {
  10250. let conds = [];
  10251. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10252. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10253. let act = r.action || 'accept';
  10254. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10255. }
  10256. }
  10257. const comEl = document.getElementById('modal-rf-comment');
  10258. if (comEl) comEl.value = r.comment || '';
  10259. const disEl = document.getElementById('modal-rf-disabled');
  10260. if (disEl) disEl.checked = !!r.disabled;
  10261. const modal = document.getElementById('modal-routing-filter');
  10262. if (modal) modal.classList.remove('hidden');
  10263. }
  10264. function closeRoutingFilterModal() {
  10265. const modal = document.getElementById('modal-routing-filter');
  10266. if (modal) modal.classList.add('hidden');
  10267. }
  10268. async function submitRoutingFilter(e) {
  10269. if (e) e.preventDefault();
  10270. const payload = {
  10271. id: document.getElementById('modal-rf-id').value,
  10272. chain: document.getElementById('modal-rf-chain').value.trim(),
  10273. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10274. rule: document.getElementById('modal-rf-rule').value.trim(),
  10275. comment: document.getElementById('modal-rf-comment').value.trim(),
  10276. disabled: document.getElementById('modal-rf-disabled').checked
  10277. };
  10278. try {
  10279. const res = await fetch(`${API_BASE}/routing/filters`, {
  10280. method: 'POST',
  10281. headers: { 'Content-Type': 'application/json' },
  10282. body: JSON.stringify(payload)
  10283. });
  10284. if (res.ok) {
  10285. closeRoutingFilterModal();
  10286. showToast('Success', 'Routing filter rule saved', 'success');
  10287. loadDynamicRouting();
  10288. } else {
  10289. const err = await res.json();
  10290. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10291. }
  10292. } catch (err) {
  10293. showToast('Error', err.message, 'error');
  10294. }
  10295. }
  10296. async function applyRoutingFilterForm() {
  10297. const payload = {
  10298. id: document.getElementById('modal-rf-id').value,
  10299. chain: document.getElementById('modal-rf-chain').value.trim(),
  10300. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10301. rule: document.getElementById('modal-rf-rule').value.trim(),
  10302. comment: document.getElementById('modal-rf-comment').value.trim(),
  10303. disabled: document.getElementById('modal-rf-disabled').checked
  10304. };
  10305. try {
  10306. const res = await fetch(`${API_BASE}/routing/filters`, {
  10307. method: 'POST',
  10308. headers: { 'Content-Type': 'application/json' },
  10309. body: JSON.stringify(payload)
  10310. });
  10311. if (res.ok) {
  10312. const data = await res.json();
  10313. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10314. showToast('Applied', 'Routing filter configuration applied', 'success');
  10315. loadDynamicRouting();
  10316. } else {
  10317. const err = await res.json();
  10318. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10319. }
  10320. } catch (err) {
  10321. showToast('Error', err.message, 'error');
  10322. }
  10323. }
  10324. async function moveRoutingFilterOrder(id, delta) {
  10325. const list = state.routingFilters || [];
  10326. const idx = list.findIndex(r => r.id === id);
  10327. if (idx < 0) return;
  10328. const targetIdx = idx + delta;
  10329. if (targetIdx < 0 || targetIdx >= list.length) return;
  10330. const currentOrder = list[idx].rule_order || 10;
  10331. const targetOrder = list[targetIdx].rule_order || 20;
  10332. list[idx].rule_order = targetOrder;
  10333. list[targetIdx].rule_order = currentOrder;
  10334. try {
  10335. await fetch(`${API_BASE}/routing/filters`, {
  10336. method: 'POST',
  10337. headers: { 'Content-Type': 'application/json' },
  10338. body: JSON.stringify(list[idx])
  10339. });
  10340. await fetch(`${API_BASE}/routing/filters`, {
  10341. method: 'POST',
  10342. headers: { 'Content-Type': 'application/json' },
  10343. body: JSON.stringify(list[targetIdx])
  10344. });
  10345. loadDynamicRouting();
  10346. } catch (e) {
  10347. console.error('Reorder error:', e);
  10348. }
  10349. }
  10350. async function deleteRoutingFilter(id) {
  10351. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10352. try {
  10353. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10354. if (res.ok) {
  10355. showToast('Deleted', 'Routing filter rule removed', 'info');
  10356. loadDynamicRouting();
  10357. } else {
  10358. const err = await res.json();
  10359. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10360. }
  10361. } catch (err) {
  10362. showToast('Error', err.message, 'error');
  10363. }
  10364. }
  10365. async function toggleRoutingFilterState(id, disabled) {
  10366. try {
  10367. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10368. method: 'POST',
  10369. headers: { 'Content-Type': 'application/json' },
  10370. body: JSON.stringify({ disabled })
  10371. });
  10372. if (res.ok) {
  10373. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10374. loadDynamicRouting();
  10375. } else {
  10376. const err = await res.json();
  10377. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10378. }
  10379. } catch (err) {
  10380. showToast('Error', err.message, 'error');
  10381. }
  10382. }
  10383. // -------------------------------------------------------------
  10384. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10385. // -------------------------------------------------------------
  10386. function openAddSelectRuleModal() {
  10387. document.getElementById('modal-rf-sr-id').value = '';
  10388. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10389. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10390. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10391. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10392. document.getElementById('modal-rf-sr-comment').value = '';
  10393. document.getElementById('modal-rf-sr-disabled').checked = false;
  10394. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10395. }
  10396. function openEditSelectRuleModal(id) {
  10397. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10398. if (!r) return;
  10399. document.getElementById('modal-rf-sr-id').value = r.id;
  10400. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10401. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10402. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10403. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10404. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10405. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10406. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10407. }
  10408. function closeSelectRuleModal() {
  10409. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10410. }
  10411. async function submitSelectRule(e) {
  10412. e.preventDefault();
  10413. const payload = {
  10414. id: document.getElementById('modal-rf-sr-id').value,
  10415. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10416. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10417. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10418. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10419. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10420. };
  10421. try {
  10422. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10423. method: 'POST',
  10424. headers: { 'Content-Type': 'application/json' },
  10425. body: JSON.stringify(payload)
  10426. });
  10427. if (res.ok) {
  10428. closeSelectRuleModal();
  10429. showToast('Success', 'Select rule saved', 'success');
  10430. loadDynamicRouting();
  10431. } else {
  10432. const err = await res.json();
  10433. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10434. }
  10435. } catch (err) {
  10436. showToast('Error', err.message, 'error');
  10437. }
  10438. }
  10439. async function deleteSelectRule(id) {
  10440. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10441. try {
  10442. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10443. if (res.ok) {
  10444. showToast('Deleted', 'Select rule removed', 'info');
  10445. loadDynamicRouting();
  10446. } else {
  10447. const err = await res.json();
  10448. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10449. }
  10450. } catch (err) {
  10451. showToast('Error', err.message, 'error');
  10452. }
  10453. }
  10454. async function toggleSelectRuleState(id, disabled) {
  10455. try {
  10456. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10457. method: 'POST',
  10458. headers: { 'Content-Type': 'application/json' },
  10459. body: JSON.stringify({ disabled })
  10460. });
  10461. if (res.ok) {
  10462. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10463. loadDynamicRouting();
  10464. } else {
  10465. const err = await res.json();
  10466. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10467. }
  10468. } catch (err) {
  10469. showToast('Error', err.message, 'error');
  10470. }
  10471. }
  10472. // -------------------------------------------------------------
  10473. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10474. // -------------------------------------------------------------
  10475. function openAddCommunityListModal() {
  10476. document.getElementById('modal-rf-cl-id').value = '';
  10477. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10478. document.getElementById('modal-rf-cl-name').value = '';
  10479. document.getElementById('modal-rf-cl-communities').value = '';
  10480. document.getElementById('modal-rf-cl-regexp').value = '';
  10481. document.getElementById('modal-rf-cl-comment').value = '';
  10482. document.getElementById('modal-rf-cl-disabled').checked = false;
  10483. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10484. }
  10485. function openEditCommunityListModal(id) {
  10486. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10487. if (!cl) return;
  10488. document.getElementById('modal-rf-cl-id').value = cl.id;
  10489. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10490. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10491. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10492. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10493. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10494. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10495. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10496. }
  10497. function closeCommunityListModal() {
  10498. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10499. }
  10500. async function submitCommunityList(e) {
  10501. e.preventDefault();
  10502. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10503. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10504. const payload = {
  10505. id: document.getElementById('modal-rf-cl-id').value,
  10506. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10507. communities: comms,
  10508. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10509. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10510. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10511. };
  10512. try {
  10513. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10514. method: 'POST',
  10515. headers: { 'Content-Type': 'application/json' },
  10516. body: JSON.stringify(payload)
  10517. });
  10518. if (res.ok) {
  10519. closeCommunityListModal();
  10520. showToast('Success', 'Community list saved', 'success');
  10521. loadDynamicRouting();
  10522. } else {
  10523. const err = await res.json();
  10524. showToast('Error', err.error || 'Failed to save community list', 'error');
  10525. }
  10526. } catch (err) {
  10527. showToast('Error', err.message, 'error');
  10528. }
  10529. }
  10530. async function deleteCommunityList(id) {
  10531. if (!confirm('Are you sure you want to delete this community list?')) return;
  10532. try {
  10533. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10534. if (res.ok) {
  10535. showToast('Deleted', 'Community list removed', 'info');
  10536. loadDynamicRouting();
  10537. } else {
  10538. const err = await res.json();
  10539. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10540. }
  10541. } catch (err) {
  10542. showToast('Error', err.message, 'error');
  10543. }
  10544. }
  10545. async function toggleCommunityListState(id, disabled) {
  10546. try {
  10547. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10548. method: 'POST',
  10549. headers: { 'Content-Type': 'application/json' },
  10550. body: JSON.stringify({ disabled })
  10551. });
  10552. if (res.ok) {
  10553. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10554. loadDynamicRouting();
  10555. } else {
  10556. const err = await res.json();
  10557. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10558. }
  10559. } catch (err) {
  10560. showToast('Error', err.message, 'error');
  10561. }
  10562. }
  10563. // -------------------------------------------------------------
  10564. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10565. // -------------------------------------------------------------
  10566. function openAddASListModal() {
  10567. document.getElementById('modal-rf-al-id').value = '';
  10568. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10569. document.getElementById('modal-rf-al-name').value = '';
  10570. document.getElementById('modal-rf-al-range').value = '';
  10571. document.getElementById('modal-rf-al-comment').value = '';
  10572. document.getElementById('modal-rf-al-disabled').checked = false;
  10573. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10574. }
  10575. function openEditASListModal(id) {
  10576. const al = (state.routingASLists || []).find(item => item.id === id);
  10577. if (!al) return;
  10578. document.getElementById('modal-rf-al-id').value = al.id;
  10579. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10580. document.getElementById('modal-rf-al-name').value = al.name || '';
  10581. document.getElementById('modal-rf-al-range').value = al.range || '';
  10582. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10583. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10584. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10585. }
  10586. function closeASListModal() {
  10587. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10588. }
  10589. async function submitASList(e) {
  10590. e.preventDefault();
  10591. const payload = {
  10592. id: document.getElementById('modal-rf-al-id').value,
  10593. name: document.getElementById('modal-rf-al-name').value.trim(),
  10594. range: document.getElementById('modal-rf-al-range').value.trim(),
  10595. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10596. disabled: document.getElementById('modal-rf-al-disabled').checked
  10597. };
  10598. try {
  10599. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10600. method: 'POST',
  10601. headers: { 'Content-Type': 'application/json' },
  10602. body: JSON.stringify(payload)
  10603. });
  10604. if (res.ok) {
  10605. closeASListModal();
  10606. showToast('Success', 'AS number list saved', 'success');
  10607. loadDynamicRouting();
  10608. } else {
  10609. const err = await res.json();
  10610. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10611. }
  10612. } catch (err) {
  10613. showToast('Error', err.message, 'error');
  10614. }
  10615. }
  10616. async function deleteASList(id) {
  10617. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10618. try {
  10619. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10620. if (res.ok) {
  10621. showToast('Deleted', 'AS list removed', 'info');
  10622. loadDynamicRouting();
  10623. } else {
  10624. const err = await res.json();
  10625. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10626. }
  10627. } catch (err) {
  10628. showToast('Error', err.message, 'error');
  10629. }
  10630. }
  10631. async function toggleASListState(id, disabled) {
  10632. try {
  10633. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10634. method: 'POST',
  10635. headers: { 'Content-Type': 'application/json' },
  10636. body: JSON.stringify({ disabled })
  10637. });
  10638. if (res.ok) {
  10639. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10640. loadDynamicRouting();
  10641. } else {
  10642. const err = await res.json();
  10643. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10644. }
  10645. } catch (err) {
  10646. showToast('Error', err.message, 'error');
  10647. }
  10648. }
  10649. // ==========================================
  10650. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10651. // ==========================================
  10652. function loadToolsView() {
  10653. populateToolsInterfaces();
  10654. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10655. }
  10656. function populateToolsInterfaces() {
  10657. const pingSel = document.getElementById('tools-ping-iface');
  10658. const traceSel = document.getElementById('tools-tr-iface');
  10659. let opts = '<option value="">Auto (Default Route)</option>';
  10660. if (Array.isArray(state.interfaces)) {
  10661. state.interfaces.forEach(iface => {
  10662. if (iface.name) {
  10663. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10664. }
  10665. });
  10666. }
  10667. if (pingSel) {
  10668. const cur = pingSel.value;
  10669. pingSel.innerHTML = opts;
  10670. if (cur) pingSel.value = cur;
  10671. }
  10672. if (traceSel) {
  10673. const cur = traceSel.value;
  10674. traceSel.innerHTML = opts;
  10675. if (cur) traceSel.value = cur;
  10676. }
  10677. }
  10678. function switchToolsSubTab(subTab) {
  10679. state.activeToolsSubTab = subTab;
  10680. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10681. tabs.forEach(t => {
  10682. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10683. const view = document.getElementById(`tools-view-${t}`);
  10684. if (btn) {
  10685. if (t === subTab) {
  10686. 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';
  10687. } else {
  10688. 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';
  10689. }
  10690. }
  10691. if (view) {
  10692. if (t === subTab) {
  10693. view.classList.remove('hidden');
  10694. } else {
  10695. view.classList.add('hidden');
  10696. }
  10697. }
  10698. });
  10699. }
  10700. function setPortPreset(port) {
  10701. const input = document.getElementById('tools-port-num');
  10702. if (input) input.value = port;
  10703. }
  10704. let pingAbortController = null;
  10705. let tracerouteAbortController = null;
  10706. function clearPingTable() {
  10707. const tbody = document.getElementById('tools-ping-tbody');
  10708. if (tbody) tbody.innerHTML = '';
  10709. const rawEl = document.getElementById('tools-ping-raw');
  10710. if (rawEl) rawEl.innerText = '';
  10711. const sentEl = document.getElementById('tools-ping-stat-sent');
  10712. if (sentEl) sentEl.innerText = '0';
  10713. const recvEl = document.getElementById('tools-ping-stat-recv');
  10714. if (recvEl) recvEl.innerText = '0';
  10715. const lossEl = document.getElementById('tools-ping-stat-loss');
  10716. if (lossEl) lossEl.innerText = '0%';
  10717. const avgEl = document.getElementById('tools-ping-stat-avg');
  10718. if (avgEl) avgEl.innerText = '0 ms';
  10719. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10720. if (minMaxEl) minMaxEl.innerText = '-';
  10721. const badge = document.getElementById('tools-ping-status-badge');
  10722. if (badge) {
  10723. badge.className = '';
  10724. badge.innerText = '';
  10725. }
  10726. }
  10727. function clearTracerouteTable() {
  10728. const tbody = document.getElementById('tools-tr-tbody');
  10729. if (tbody) tbody.innerHTML = '';
  10730. const rawEl = document.getElementById('tools-tr-raw');
  10731. if (rawEl) rawEl.innerText = '';
  10732. const statHops = document.getElementById('tools-tr-hops-count');
  10733. if (statHops) statHops.innerText = '0 Hops';
  10734. }
  10735. function resetPingButton() {
  10736. const btn = document.getElementById('tools-ping-btn');
  10737. const btnText = document.getElementById('tools-ping-btn-text');
  10738. const spinner = document.getElementById('tools-ping-spinner');
  10739. if (btn) {
  10740. btn.disabled = false;
  10741. 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';
  10742. }
  10743. if (btnText) btnText.innerText = 'Start Ping';
  10744. if (spinner) spinner.classList.add('hidden');
  10745. }
  10746. function setPingRunningButton() {
  10747. const btn = document.getElementById('tools-ping-btn');
  10748. const btnText = document.getElementById('tools-ping-btn-text');
  10749. const spinner = document.getElementById('tools-ping-spinner');
  10750. if (btn) {
  10751. btn.disabled = false;
  10752. 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';
  10753. }
  10754. if (btnText) btnText.innerText = 'Stop Ping';
  10755. if (spinner) spinner.classList.remove('hidden');
  10756. }
  10757. function resetTracerouteButton() {
  10758. const btn = document.getElementById('tools-tr-btn');
  10759. const btnText = document.getElementById('tools-tr-btn-text');
  10760. const spinner = document.getElementById('tools-tr-spinner');
  10761. if (btn) {
  10762. btn.disabled = false;
  10763. 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';
  10764. }
  10765. if (btnText) btnText.innerText = 'Start Traceroute';
  10766. if (spinner) spinner.classList.add('hidden');
  10767. }
  10768. function setTracerouteRunningButton() {
  10769. const btn = document.getElementById('tools-tr-btn');
  10770. const btnText = document.getElementById('tools-tr-btn-text');
  10771. const spinner = document.getElementById('tools-tr-spinner');
  10772. if (btn) {
  10773. btn.disabled = false;
  10774. 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';
  10775. }
  10776. if (btnText) btnText.innerText = 'Stop Traceroute';
  10777. if (spinner) spinner.classList.remove('hidden');
  10778. }
  10779. async function executePing(e) {
  10780. if (e) e.preventDefault();
  10781. // If already running, clicking the button stops the stream!
  10782. if (pingAbortController) {
  10783. pingAbortController.abort();
  10784. pingAbortController = null;
  10785. resetPingButton();
  10786. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10787. return;
  10788. }
  10789. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10790. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10791. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10792. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10793. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10794. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10795. if (!target) {
  10796. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10797. return;
  10798. }
  10799. clearPingTable();
  10800. const resCard = document.getElementById('tools-ping-results');
  10801. if (resCard) resCard.classList.remove('hidden');
  10802. pingAbortController = new AbortController();
  10803. setPingRunningButton();
  10804. try {
  10805. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10806. method: 'POST',
  10807. headers: { 'Content-Type': 'application/json' },
  10808. body: JSON.stringify({
  10809. target,
  10810. count,
  10811. size,
  10812. timeout,
  10813. interface: iface,
  10814. dont_frag: dontFrag
  10815. }),
  10816. signal: pingAbortController.signal
  10817. });
  10818. if (!res.ok) {
  10819. const errText = await res.text();
  10820. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10821. resetPingButton();
  10822. pingAbortController = null;
  10823. return;
  10824. }
  10825. const reader = res.body.getReader();
  10826. const decoder = new TextDecoder('utf-8');
  10827. let buffer = '';
  10828. while (true) {
  10829. const { done, value } = await reader.read();
  10830. if (done) break;
  10831. buffer += decoder.decode(value, { stream: true });
  10832. const blocks = buffer.split('\n\n');
  10833. buffer = blocks.pop() || '';
  10834. for (const block of blocks) {
  10835. const trimmed = block.trim();
  10836. if (!trimmed) continue;
  10837. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10838. try {
  10839. const evt = JSON.parse(line);
  10840. handleLivePingEvent(evt);
  10841. } catch (parseErr) {
  10842. console.warn('Ping SSE parse error:', parseErr, line);
  10843. }
  10844. }
  10845. }
  10846. } catch (err) {
  10847. if (err.name === 'AbortError') {
  10848. // User aborted normally
  10849. } else {
  10850. showToast('Ping Error', err.message, 'error');
  10851. }
  10852. } finally {
  10853. pingAbortController = null;
  10854. resetPingButton();
  10855. }
  10856. }
  10857. function handleLivePingEvent(evt) {
  10858. const sentEl = document.getElementById('tools-ping-stat-sent');
  10859. const recvEl = document.getElementById('tools-ping-stat-recv');
  10860. const lossEl = document.getElementById('tools-ping-stat-loss');
  10861. const avgEl = document.getElementById('tools-ping-stat-avg');
  10862. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10863. const badge = document.getElementById('tools-ping-status-badge');
  10864. const tbody = document.getElementById('tools-ping-tbody');
  10865. const rawEl = document.getElementById('tools-ping-raw');
  10866. if (evt.raw && rawEl) {
  10867. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10868. rawEl.scrollTop = rawEl.scrollHeight;
  10869. }
  10870. if (evt.type === 'reply') {
  10871. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10872. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10873. if (lossEl && evt.packet_loss_pct !== undefined) {
  10874. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10875. lossEl.className = evt.packet_loss_pct === 0
  10876. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10877. : (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');
  10878. }
  10879. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10880. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10881. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10882. }
  10883. if (badge) {
  10884. if (evt.packet_loss_pct === 0) {
  10885. 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';
  10886. badge.innerText = '100% OK';
  10887. } else {
  10888. 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';
  10889. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10890. }
  10891. }
  10892. if (tbody) {
  10893. const tr = document.createElement('tr');
  10894. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10895. tr.innerHTML = `
  10896. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10897. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10898. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10899. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10900. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10901. <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>
  10902. `;
  10903. tbody.appendChild(tr);
  10904. }
  10905. } else if (evt.type === 'timeout') {
  10906. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10907. if (lossEl && evt.packet_loss_pct !== undefined) {
  10908. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10909. 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';
  10910. }
  10911. if (badge) {
  10912. 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';
  10913. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10914. }
  10915. if (tbody) {
  10916. const tr = document.createElement('tr');
  10917. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10918. tr.innerHTML = `
  10919. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10920. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10921. <td class="py-2 px-3 text-slate-600">--</td>
  10922. <td class="py-2 px-3 text-slate-600">--</td>
  10923. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10924. <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>
  10925. `;
  10926. tbody.appendChild(tr);
  10927. }
  10928. } else if (evt.type === 'unreach') {
  10929. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10930. if (lossEl && evt.packet_loss_pct !== undefined) {
  10931. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10932. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10933. }
  10934. if (badge) {
  10935. 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';
  10936. badge.innerText = 'UNREACHABLE';
  10937. }
  10938. if (tbody) {
  10939. const tr = document.createElement('tr');
  10940. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10941. tr.innerHTML = `
  10942. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10943. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10944. <td class="py-2 px-3 text-slate-600">--</td>
  10945. <td class="py-2 px-3 text-slate-600">--</td>
  10946. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10947. <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>
  10948. `;
  10949. tbody.appendChild(tr);
  10950. }
  10951. } else if (evt.type === 'stats') {
  10952. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10953. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10954. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10955. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10956. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10957. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10958. }
  10959. } else if (evt.type === 'done') {
  10960. 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');
  10961. }
  10962. }
  10963. async function executeTraceroute(e) {
  10964. if (e) e.preventDefault();
  10965. if (tracerouteAbortController) {
  10966. tracerouteAbortController.abort();
  10967. tracerouteAbortController = null;
  10968. resetTracerouteButton();
  10969. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10970. return;
  10971. }
  10972. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10973. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10974. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10975. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10976. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10977. if (!target) {
  10978. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10979. return;
  10980. }
  10981. clearTracerouteTable();
  10982. const resCard = document.getElementById('tools-tr-results');
  10983. if (resCard) resCard.classList.remove('hidden');
  10984. tracerouteAbortController = new AbortController();
  10985. setTracerouteRunningButton();
  10986. try {
  10987. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10988. method: 'POST',
  10989. headers: { 'Content-Type': 'application/json' },
  10990. body: JSON.stringify({
  10991. target,
  10992. max_hops: maxHops,
  10993. protocol,
  10994. interface: iface,
  10995. resolve
  10996. }),
  10997. signal: tracerouteAbortController.signal
  10998. });
  10999. if (!res.ok) {
  11000. const errText = await res.text();
  11001. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11002. resetTracerouteButton();
  11003. tracerouteAbortController = null;
  11004. return;
  11005. }
  11006. const reader = res.body.getReader();
  11007. const decoder = new TextDecoder('utf-8');
  11008. let buffer = '';
  11009. while (true) {
  11010. const { done, value } = await reader.read();
  11011. if (done) break;
  11012. buffer += decoder.decode(value, { stream: true });
  11013. const blocks = buffer.split('\n\n');
  11014. buffer = blocks.pop() || '';
  11015. for (const block of blocks) {
  11016. const trimmed = block.trim();
  11017. if (!trimmed) continue;
  11018. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11019. try {
  11020. const evt = JSON.parse(line);
  11021. handleLiveTracerouteEvent(evt);
  11022. } catch (parseErr) {
  11023. console.warn('Traceroute SSE parse error:', parseErr, line);
  11024. }
  11025. }
  11026. }
  11027. } catch (err) {
  11028. if (err.name === 'AbortError') {
  11029. // User aborted normally
  11030. } else {
  11031. showToast('Traceroute Error', err.message, 'error');
  11032. }
  11033. } finally {
  11034. tracerouteAbortController = null;
  11035. resetTracerouteButton();
  11036. }
  11037. }
  11038. function handleLiveTracerouteEvent(evt) {
  11039. const statHops = document.getElementById('tools-tr-hops-count');
  11040. const tbody = document.getElementById('tools-tr-tbody');
  11041. const rawEl = document.getElementById('tools-tr-raw');
  11042. if (evt.raw && rawEl) {
  11043. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11044. rawEl.scrollTop = rawEl.scrollHeight;
  11045. }
  11046. if (evt.hops_count !== undefined && statHops) {
  11047. statHops.innerText = `${evt.hops_count} Hops`;
  11048. }
  11049. if (evt.type === 'hop' && evt.hop && tbody) {
  11050. const h = evt.hop;
  11051. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11052. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11053. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11054. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11055. const tr = document.createElement('tr');
  11056. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11057. tr.innerHTML = `
  11058. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11059. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11060. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11061. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11062. <td class="py-2.5 px-3 text-right">
  11063. ${isTimeout
  11064. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11065. : '<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>'}
  11066. </td>
  11067. `;
  11068. tbody.appendChild(tr);
  11069. } else if (evt.type === 'done') {
  11070. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11071. }
  11072. }
  11073. async function executeMTR(e) {
  11074. if (e) e.preventDefault();
  11075. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11076. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11077. if (!target) {
  11078. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11079. return;
  11080. }
  11081. const btn = document.getElementById('tools-mtr-btn');
  11082. const spinner = document.getElementById('tools-mtr-spinner');
  11083. if (btn) btn.disabled = true;
  11084. if (spinner) spinner.classList.remove('hidden');
  11085. try {
  11086. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11087. method: 'POST',
  11088. headers: { 'Content-Type': 'application/json' },
  11089. body: JSON.stringify({ target, count: cycles })
  11090. });
  11091. const data = await res.json();
  11092. if (!res.ok) {
  11093. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11094. return;
  11095. }
  11096. const resCard = document.getElementById('tools-mtr-results');
  11097. if (resCard) resCard.classList.remove('hidden');
  11098. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11099. const statHops = document.getElementById('tools-mtr-hops-count');
  11100. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11101. const tbody = document.getElementById('tools-mtr-tbody');
  11102. if (tbody) {
  11103. if (hopsCount > 0) {
  11104. tbody.innerHTML = data.hops.map(h => {
  11105. 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');
  11106. return `
  11107. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11108. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11109. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11110. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11111. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11112. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11113. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11114. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11115. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11116. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11117. </tr>
  11118. `;
  11119. }).join('');
  11120. } else {
  11121. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11122. }
  11123. }
  11124. const rawEl = document.getElementById('tools-mtr-raw');
  11125. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11126. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11127. } catch (err) {
  11128. showToast('MTR Error', err.message, 'error');
  11129. } finally {
  11130. if (btn) btn.disabled = false;
  11131. if (spinner) spinner.classList.add('hidden');
  11132. }
  11133. }
  11134. async function executeDNS(e) {
  11135. if (e) e.preventDefault();
  11136. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11137. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11138. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11139. if (!domain) {
  11140. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11141. return;
  11142. }
  11143. const btn = document.getElementById('tools-dns-btn');
  11144. const spinner = document.getElementById('tools-dns-spinner');
  11145. if (btn) btn.disabled = true;
  11146. if (spinner) spinner.classList.remove('hidden');
  11147. try {
  11148. const res = await fetch(`${API_BASE}/tools/dns`, {
  11149. method: 'POST',
  11150. headers: { 'Content-Type': 'application/json' },
  11151. body: JSON.stringify({ domain, type, server })
  11152. });
  11153. const data = await res.json();
  11154. if (!res.ok) {
  11155. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11156. return;
  11157. }
  11158. const resCard = document.getElementById('tools-dns-results');
  11159. if (resCard) resCard.classList.remove('hidden');
  11160. const metaEl = document.getElementById('tools-dns-meta');
  11161. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11162. const tbody = document.getElementById('tools-dns-tbody');
  11163. if (tbody) {
  11164. if (Array.isArray(data.records) && data.records.length > 0) {
  11165. tbody.innerHTML = data.records.map(r => `
  11166. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11167. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11168. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11169. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11170. <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>
  11171. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11172. </tr>
  11173. `).join('');
  11174. } else {
  11175. 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>`;
  11176. }
  11177. }
  11178. const rawEl = document.getElementById('tools-dns-raw');
  11179. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11180. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11181. } catch (err) {
  11182. showToast('DNS Error', err.message, 'error');
  11183. } finally {
  11184. if (btn) btn.disabled = false;
  11185. if (spinner) spinner.classList.add('hidden');
  11186. }
  11187. }
  11188. async function executePortProbe(e) {
  11189. if (e) e.preventDefault();
  11190. const target = document.getElementById('tools-port-target')?.value?.trim();
  11191. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11192. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11193. if (!target || !port) {
  11194. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11195. return;
  11196. }
  11197. const btn = document.getElementById('tools-port-btn');
  11198. const spinner = document.getElementById('tools-port-spinner');
  11199. if (btn) btn.disabled = true;
  11200. if (spinner) spinner.classList.remove('hidden');
  11201. try {
  11202. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11203. method: 'POST',
  11204. headers: { 'Content-Type': 'application/json' },
  11205. body: JSON.stringify({ target, port, timeout })
  11206. });
  11207. const data = await res.json();
  11208. if (!res.ok) {
  11209. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11210. return;
  11211. }
  11212. const resCard = document.getElementById('tools-port-results');
  11213. if (resCard) resCard.classList.remove('hidden');
  11214. const banner = document.getElementById('tools-port-banner');
  11215. const icon = document.getElementById('tools-port-icon');
  11216. const title = document.getElementById('tools-port-title');
  11217. const sub = document.getElementById('tools-port-sub');
  11218. const latency = document.getElementById('tools-port-latency');
  11219. if (data.open) {
  11220. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11221. if (icon) {
  11222. 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';
  11223. icon.innerText = '✓';
  11224. }
  11225. if (title) {
  11226. title.className = 'text-sm font-bold text-emerald-300';
  11227. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11228. }
  11229. if (sub) {
  11230. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11231. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11232. }
  11233. if (latency) {
  11234. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11235. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11236. }
  11237. } else {
  11238. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11239. if (icon) {
  11240. 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';
  11241. icon.innerText = '✕';
  11242. }
  11243. if (title) {
  11244. title.className = 'text-sm font-bold text-rose-300';
  11245. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11246. }
  11247. if (sub) {
  11248. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11249. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11250. }
  11251. if (latency) {
  11252. latency.className = 'text-base font-bold font-mono text-slate-500';
  11253. latency.innerText = '--';
  11254. }
  11255. }
  11256. const rawEl = document.getElementById('tools-port-raw');
  11257. 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'}`);
  11258. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11259. } catch (err) {
  11260. showToast('Probe Error', err.message, 'error');
  11261. } finally {
  11262. if (btn) btn.disabled = false;
  11263. if (spinner) spinner.classList.add('hidden');
  11264. }
  11265. }
  11266. // ==========================================
  11267. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11268. // ==========================================
  11269. async function loadDHCPClients(showToastMsg = false) {
  11270. try {
  11271. const [clientsRes, sumRes] = await Promise.all([
  11272. fetch(`${API_BASE}/dhcp/clients`),
  11273. fetch(`${API_BASE}/dhcp/clients/summary`)
  11274. ]);
  11275. if (clientsRes.ok) {
  11276. state.dhcpClients = await clientsRes.json();
  11277. }
  11278. if (sumRes.ok) {
  11279. state.dhcpSummary = await sumRes.json();
  11280. }
  11281. renderDHCPClients();
  11282. updateDHCPSummaryCards();
  11283. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11284. if (bDhcp && state.dhcpSummary) {
  11285. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11286. }
  11287. if (showToastMsg) {
  11288. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11289. }
  11290. } catch (err) {
  11291. console.error('Failed to load DHCP clients:', err);
  11292. if (showToastMsg) {
  11293. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11294. }
  11295. }
  11296. }
  11297. function updateDHCPSummaryCards() {
  11298. const sum = state.dhcpSummary || {
  11299. total_clients: (state.dhcpClients || []).length,
  11300. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11301. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11302. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11303. };
  11304. const totalEl = document.getElementById('dhcp-stat-total');
  11305. const boundEl = document.getElementById('dhcp-stat-bound');
  11306. const searchEl = document.getElementById('dhcp-stat-searching');
  11307. const disEl = document.getElementById('dhcp-stat-disabled');
  11308. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11309. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11310. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11311. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11312. }
  11313. function renderDHCPClients() {
  11314. const tbody = document.getElementById('dhcp-clients-tbody');
  11315. const emptyState = document.getElementById('dhcp-clients-empty');
  11316. if (!tbody) return;
  11317. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11318. if (clients.length === 0) {
  11319. tbody.innerHTML = '';
  11320. if (emptyState) emptyState.classList.remove('hidden');
  11321. return;
  11322. }
  11323. if (emptyState) emptyState.classList.add('hidden');
  11324. tbody.innerHTML = clients.map(c => {
  11325. let statusBadge = '';
  11326. if (!c.enabled) {
  11327. 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>';
  11328. } else if (c.status === 'bound') {
  11329. 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>';
  11330. } else if (c.status === 'searching') {
  11331. 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>';
  11332. } else if (c.status === 'stopped') {
  11333. 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>';
  11334. } else {
  11335. 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>`;
  11336. }
  11337. 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>';
  11338. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11339. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11340. 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>';
  11341. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11342. // Option flags
  11343. const flags = [];
  11344. 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>');
  11345. 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>');
  11346. 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>');
  11347. 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>`);
  11348. return `
  11349. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11350. <td class="py-3 px-4">
  11351. <div class="flex items-center gap-2">
  11352. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11353. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11354. </div>
  11355. </td>
  11356. <td class="py-3 px-4">${statusBadge}</td>
  11357. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11358. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11359. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11360. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11361. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11362. <td class="py-3 px-4">
  11363. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11364. </td>
  11365. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11366. ${c.enabled ? `
  11367. <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>
  11368. <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>
  11369. <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>
  11370. ` : `
  11371. <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>
  11372. `}
  11373. <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>
  11374. <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>
  11375. </td>
  11376. </tr>
  11377. `;
  11378. }).join('');
  11379. }
  11380. function openDHCPClientModal(clientId = null) {
  11381. const modal = document.getElementById('modal-dhcp-client');
  11382. if (!modal) return;
  11383. const title = document.getElementById('modal-dhcp-title');
  11384. const idInput = document.getElementById('modal-dhcp-id');
  11385. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11386. const distInput = document.getElementById('modal-dhcp-distance');
  11387. const commentInput = document.getElementById('modal-dhcp-comment');
  11388. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11389. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11390. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11391. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11392. // Populate interfaces
  11393. if (ifaceSelect) {
  11394. let opts = '<option value="">Select interface...</option>';
  11395. const allIfaces = state.interfaces || [];
  11396. const allVlans = state.vlans || [];
  11397. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11398. // Group 1: Physical & Bridge Interfaces
  11399. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11400. allIfaces.forEach(i => {
  11401. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11402. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11403. });
  11404. opts += '</optgroup>';
  11405. // Group 2: VLAN Interfaces
  11406. if (allVlans.length > 0) {
  11407. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11408. allVlans.forEach(v => {
  11409. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11410. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11411. });
  11412. opts += '</optgroup>';
  11413. }
  11414. ifaceSelect.innerHTML = opts;
  11415. }
  11416. if (clientId) {
  11417. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11418. if (client) {
  11419. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11420. if (idInput) idInput.value = client.id;
  11421. if (ifaceSelect) {
  11422. ifaceSelect.value = client.interface;
  11423. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11424. }
  11425. if (distInput) distInput.value = client.default_route_distance || 1;
  11426. if (commentInput) commentInput.value = client.comment || '';
  11427. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11428. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11429. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11430. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11431. }
  11432. } else {
  11433. if (title) title.innerText = 'Add DHCP Client';
  11434. if (idInput) idInput.value = '';
  11435. if (ifaceSelect) {
  11436. ifaceSelect.value = '';
  11437. ifaceSelect.disabled = false;
  11438. }
  11439. if (distInput) distInput.value = 1;
  11440. if (commentInput) commentInput.value = '';
  11441. if (defRouteCheck) defRouteCheck.checked = true;
  11442. if (peerDnsCheck) peerDnsCheck.checked = true;
  11443. if (peerNtpCheck) peerNtpCheck.checked = true;
  11444. if (enabledCheck) enabledCheck.checked = true;
  11445. }
  11446. modal.classList.remove('hidden');
  11447. }
  11448. function openDHCPClientModalForIface(ifaceName) {
  11449. openDHCPClientModal();
  11450. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11451. if (ifaceSelect && ifaceName) {
  11452. ifaceSelect.value = ifaceName;
  11453. }
  11454. }
  11455. function closeDHCPClientModal() {
  11456. const modal = document.getElementById('modal-dhcp-client');
  11457. if (modal) modal.classList.add('hidden');
  11458. }
  11459. async function submitSaveDHCPClient(e) {
  11460. if (e) e.preventDefault();
  11461. const id = document.getElementById('modal-dhcp-id')?.value;
  11462. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11463. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11464. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11465. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11466. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11467. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11468. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11469. if (!id && !iface) {
  11470. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11471. return;
  11472. }
  11473. try {
  11474. let res;
  11475. if (id) {
  11476. // PUT update
  11477. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11478. method: 'PUT',
  11479. headers: { 'Content-Type': 'application/json' },
  11480. body: JSON.stringify({
  11481. enabled,
  11482. add_default_route: defRoute,
  11483. default_route_distance: distance,
  11484. use_peer_dns: peerDns,
  11485. use_peer_ntp: peerNtp,
  11486. comment
  11487. })
  11488. });
  11489. } else {
  11490. // POST create
  11491. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11492. method: 'POST',
  11493. headers: { 'Content-Type': 'application/json' },
  11494. body: JSON.stringify({
  11495. interface: iface,
  11496. enabled,
  11497. add_default_route: defRoute,
  11498. default_route_distance: distance,
  11499. use_peer_dns: peerDns,
  11500. use_peer_ntp: peerNtp,
  11501. comment
  11502. })
  11503. });
  11504. }
  11505. const data = await res.json();
  11506. if (!res.ok) {
  11507. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11508. return;
  11509. }
  11510. closeDHCPClientModal();
  11511. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11512. await loadDHCPClients();
  11513. fetchData(); // refresh interfaces list with new lease/status
  11514. } catch (err) {
  11515. showToast('Error', err.message, 'error');
  11516. }
  11517. }
  11518. async function toggleDHCPClientState(id, enabled) {
  11519. try {
  11520. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11521. method: 'POST',
  11522. headers: { 'Content-Type': 'application/json' },
  11523. body: JSON.stringify({ enabled })
  11524. });
  11525. const data = await res.json();
  11526. if (!res.ok) {
  11527. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11528. return;
  11529. }
  11530. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11531. await loadDHCPClients();
  11532. fetchData();
  11533. } catch (err) {
  11534. showToast('Error', err.message, 'error');
  11535. }
  11536. }
  11537. async function renewDHCPClient(id) {
  11538. try {
  11539. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11540. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11541. method: 'POST'
  11542. });
  11543. const data = await res.json();
  11544. if (!res.ok) {
  11545. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11546. return;
  11547. }
  11548. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11549. setTimeout(() => {
  11550. loadDHCPClients();
  11551. fetchData();
  11552. }, 1500);
  11553. } catch (err) {
  11554. showToast('Error', err.message, 'error');
  11555. }
  11556. }
  11557. async function releaseDHCPClient(id) {
  11558. try {
  11559. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11560. method: 'POST'
  11561. });
  11562. const data = await res.json();
  11563. if (!res.ok) {
  11564. showToast('Error', data.error || 'Failed to release lease', 'error');
  11565. return;
  11566. }
  11567. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11568. await loadDHCPClients();
  11569. fetchData();
  11570. } catch (err) {
  11571. showToast('Error', err.message, 'error');
  11572. }
  11573. }
  11574. async function deleteDHCPClient(id, ifaceName) {
  11575. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11576. return;
  11577. }
  11578. try {
  11579. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11580. method: 'DELETE'
  11581. });
  11582. const data = await res.json();
  11583. if (!res.ok) {
  11584. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11585. return;
  11586. }
  11587. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11588. await loadDHCPClients();
  11589. fetchData();
  11590. } catch (err) {
  11591. showToast('Error', err.message, 'error');
  11592. }
  11593. }
  11594. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11595. async function loadDHCPServer(populate = true) {
  11596. try {
  11597. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11598. fetch(`${API_BASE}/dhcp-server/summary`),
  11599. fetch(`${API_BASE}/dhcp-server/servers`),
  11600. fetch(`${API_BASE}/dhcp-server/networks`),
  11601. fetch(`${API_BASE}/dhcp-server/leases`),
  11602. fetch(`${API_BASE}/dhcp-server/options`)
  11603. ]);
  11604. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11605. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11606. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11607. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11608. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11609. const sum = state.dhcpServerSummary || {};
  11610. const srvs = state.dhcpServers || [];
  11611. const nets = state.dhcpNetworks || [];
  11612. const leases = state.dhcpLeases || [];
  11613. const opts = state.dhcpOptions || [];
  11614. // KPI Cards
  11615. const statActive = document.getElementById('dhcp-server-stat-active');
  11616. if (statActive) {
  11617. const activeCount = srvs.filter(s => s.running).length;
  11618. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11619. }
  11620. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11621. if (statLeases) {
  11622. statLeases.innerText = leases.length;
  11623. }
  11624. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11625. if (statLeasesSub) {
  11626. const dyn = leases.filter(l => l.dynamic).length;
  11627. const st = leases.filter(l => !l.dynamic).length;
  11628. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11629. }
  11630. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11631. if (statNetworks) {
  11632. statNetworks.innerText = nets.length;
  11633. }
  11634. // Subtab Badges
  11635. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11636. if (bSrv) bSrv.innerText = srvs.length;
  11637. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11638. if (bNet) bNet.innerText = nets.length;
  11639. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11640. if (bLease) bLease.innerText = leases.length;
  11641. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11642. if (bOpt) bOpt.innerText = opts.length;
  11643. // Sidebar Badge
  11644. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11645. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11646. renderCurrentDHCPServerTab();
  11647. } catch (err) {
  11648. console.error('Failed to load DHCP Server:', err);
  11649. }
  11650. }
  11651. function switchDHCPServerTab(tab) {
  11652. state.dhcpServerTab = tab;
  11653. const tabs = ['servers', 'networks', 'leases', 'options'];
  11654. tabs.forEach(t => {
  11655. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11656. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11657. if (panel) {
  11658. if (t === tab) panel.classList.remove('hidden');
  11659. else panel.classList.add('hidden');
  11660. }
  11661. if (btn) {
  11662. if (t === tab) {
  11663. 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';
  11664. } else {
  11665. 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';
  11666. }
  11667. }
  11668. });
  11669. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11670. if (addBtn) {
  11671. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11672. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11673. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11674. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11675. }
  11676. renderCurrentDHCPServerTab();
  11677. }
  11678. function handleDHCPServerPrimaryAdd() {
  11679. const tab = state.dhcpServerTab || 'servers';
  11680. if (tab === 'servers') openAddDHCPServerModal();
  11681. else if (tab === 'networks') openAddDHCPNetworkModal();
  11682. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11683. else if (tab === 'options') openAddDHCPOptionModal();
  11684. }
  11685. function renderCurrentDHCPServerTab() {
  11686. const tab = state.dhcpServerTab || 'servers';
  11687. if (tab === 'servers') renderDHCPServers();
  11688. else if (tab === 'networks') renderDHCPNetworks();
  11689. else if (tab === 'leases') renderDHCPLeases();
  11690. else if (tab === 'options') renderDHCPOptions();
  11691. }
  11692. function renderDHCPServers() {
  11693. const tbody = document.getElementById('dhcp-server-tbody');
  11694. const empty = document.getElementById('dhcp-server-empty');
  11695. if (!tbody) return;
  11696. tbody.innerHTML = '';
  11697. const servers = state.dhcpServers || [];
  11698. if (servers.length === 0) {
  11699. empty?.classList.remove('hidden');
  11700. return;
  11701. }
  11702. empty?.classList.add('hidden');
  11703. servers.forEach(s => {
  11704. const tr = document.createElement('tr');
  11705. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11706. tr.innerHTML = `
  11707. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11708. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11709. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11710. <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>
  11711. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11712. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11713. <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>
  11714. <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>
  11715. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11716. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11717. <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>
  11718. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11719. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11720. </td>
  11721. `;
  11722. tbody.appendChild(tr);
  11723. });
  11724. }
  11725. function renderDHCPNetworks() {
  11726. const tbody = document.getElementById('dhcp-networks-tbody');
  11727. const empty = document.getElementById('dhcp-networks-empty');
  11728. if (!tbody) return;
  11729. tbody.innerHTML = '';
  11730. const networks = state.dhcpNetworks || [];
  11731. if (networks.length === 0) {
  11732. empty?.classList.remove('hidden');
  11733. return;
  11734. }
  11735. empty?.classList.add('hidden');
  11736. networks.forEach(n => {
  11737. const tr = document.createElement('tr');
  11738. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11739. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11740. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11741. tr.innerHTML = `
  11742. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11743. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11744. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11745. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11746. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11747. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11748. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11749. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11750. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11751. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11752. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11753. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11754. </td>
  11755. `;
  11756. tbody.appendChild(tr);
  11757. });
  11758. }
  11759. function renderDHCPLeases() {
  11760. const tbody = document.getElementById('dhcp-leases-tbody');
  11761. const empty = document.getElementById('dhcp-leases-empty');
  11762. if (!tbody) return;
  11763. tbody.innerHTML = '';
  11764. const leases = state.dhcpLeases || [];
  11765. if (leases.length === 0) {
  11766. empty?.classList.remove('hidden');
  11767. return;
  11768. }
  11769. empty?.classList.add('hidden');
  11770. leases.forEach(l => {
  11771. const tr = document.createElement('tr');
  11772. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11773. 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>';
  11774. const statusBadge = l.status === 'bound'
  11775. ? '<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>'
  11776. : l.status === 'static'
  11777. ? '<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>'
  11778. : '<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>';
  11779. const makeStaticBtn = l.dynamic
  11780. ? `<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>`
  11781. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11782. tr.innerHTML = `
  11783. <td class="py-2.5 px-3 text-center">${flag}</td>
  11784. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11785. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11786. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11787. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11788. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11789. <td class="py-2.5 px-3">${statusBadge}</td>
  11790. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11791. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11792. ${makeStaticBtn}
  11793. </td>
  11794. `;
  11795. tbody.appendChild(tr);
  11796. });
  11797. }
  11798. function renderDHCPOptions() {
  11799. const tbody = document.getElementById('dhcp-options-tbody');
  11800. const empty = document.getElementById('dhcp-options-empty');
  11801. if (!tbody) return;
  11802. tbody.innerHTML = '';
  11803. const options = state.dhcpOptions || [];
  11804. if (options.length === 0) {
  11805. empty?.classList.remove('hidden');
  11806. return;
  11807. }
  11808. empty?.classList.add('hidden');
  11809. options.forEach(o => {
  11810. const tr = document.createElement('tr');
  11811. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11812. tr.innerHTML = `
  11813. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11814. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11815. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11816. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11817. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11818. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11819. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11820. </td>
  11821. `;
  11822. tbody.appendChild(tr);
  11823. });
  11824. }
  11825. // ==================== MODALS & ACTIONS: SERVER ====================
  11826. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11827. const sel = document.getElementById(elemId);
  11828. if (!sel) return;
  11829. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11830. const networks = state.dhcpNetworks || [];
  11831. networks.forEach(n => {
  11832. const opt = document.createElement('option');
  11833. opt.value = n.address;
  11834. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11835. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11836. opt.selected = true;
  11837. }
  11838. sel.appendChild(opt);
  11839. });
  11840. }
  11841. function onDHCPServerNetworkChange() {
  11842. const netSel = document.getElementById('dhcp-server-modal-network');
  11843. if (!netSel) return;
  11844. const netVal = netSel.value;
  11845. if (!netVal) return;
  11846. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11847. if (!poolInput) return;
  11848. // Auto-calculate suggested address pool based on subnet CIDR
  11849. const parts = netVal.split('/');
  11850. const ip = parts[0];
  11851. const cidr = parseInt(parts[1] || '24', 10);
  11852. if (cidr === 24) {
  11853. const octets = ip.split('.');
  11854. if (octets.length === 4) {
  11855. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11856. poolInput.value = `${base}.10-${base}.254`;
  11857. }
  11858. }
  11859. }
  11860. function openAddDHCPServerModal() {
  11861. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11862. document.getElementById('dhcp-server-modal-id').value = '';
  11863. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11864. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11865. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11866. document.getElementById('dhcp-server-modal-comment').value = '';
  11867. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11868. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11869. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11870. const networks = state.dhcpNetworks || [];
  11871. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11872. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11873. if (defaultNet) {
  11874. onDHCPServerNetworkChange();
  11875. }
  11876. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11877. }
  11878. function openEditDHCPServerModal(id) {
  11879. const s = (state.dhcpServers || []).find(item => item.id === id);
  11880. if (!s) return;
  11881. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11882. document.getElementById('dhcp-server-modal-id').value = s.id;
  11883. document.getElementById('dhcp-server-modal-name').value = s.name;
  11884. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11885. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11886. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11887. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11888. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11889. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11890. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11891. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11892. }
  11893. function closeDHCPServerModal() {
  11894. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11895. }
  11896. async function submitSaveDHCPServer(e) {
  11897. e.preventDefault();
  11898. const id = document.getElementById('dhcp-server-modal-id').value;
  11899. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11900. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11901. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11902. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11903. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11904. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11905. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11906. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11907. try {
  11908. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11909. method: 'POST',
  11910. headers: { 'Content-Type': 'application/json' },
  11911. body: JSON.stringify({
  11912. id,
  11913. name,
  11914. interface: iface,
  11915. network,
  11916. address_pool: pool,
  11917. lease_time: leaseTime,
  11918. authoritative,
  11919. disabled,
  11920. comment
  11921. })
  11922. });
  11923. if (res.ok) {
  11924. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11925. closeDHCPServerModal();
  11926. loadDHCPServer(false);
  11927. fetchData(false);
  11928. } else {
  11929. const err = await res.text();
  11930. showToast('Error', err, 'error');
  11931. }
  11932. } catch (err) {
  11933. showToast('Error', err.message, 'error');
  11934. }
  11935. }
  11936. async function toggleDHCPServerState(id, disabled) {
  11937. try {
  11938. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11939. method: 'POST',
  11940. headers: { 'Content-Type': 'application/json' },
  11941. body: JSON.stringify({ disabled })
  11942. });
  11943. if (res.ok) {
  11944. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11945. loadDHCPServer(false);
  11946. fetchData(false);
  11947. }
  11948. } catch (err) {
  11949. showToast('Error', err.message, 'error');
  11950. }
  11951. }
  11952. async function deleteDHCPServer(id, name) {
  11953. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11954. try {
  11955. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11956. if (res.ok) {
  11957. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11958. loadDHCPServer(false);
  11959. fetchData(false);
  11960. }
  11961. } catch (err) {
  11962. showToast('Error', err.message, 'error');
  11963. }
  11964. }
  11965. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11966. function openAddDHCPNetworkModal() {
  11967. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11968. document.getElementById('dhcp-network-modal-id').value = '';
  11969. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11970. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11971. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11972. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11973. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11974. document.getElementById('dhcp-network-modal-tftp').value = '';
  11975. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11976. document.getElementById('dhcp-network-modal-wins').value = '';
  11977. document.getElementById('dhcp-network-modal-netmask').value = '';
  11978. document.getElementById('dhcp-network-modal-comment').value = '';
  11979. renderDHCPNetworkOptionsCheckboxes([]);
  11980. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11981. }
  11982. function openEditDHCPNetworkModal(id) {
  11983. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11984. if (!n) return;
  11985. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11986. document.getElementById('dhcp-network-modal-id').value = n.id;
  11987. document.getElementById('dhcp-network-modal-address').value = n.address;
  11988. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11989. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11990. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11991. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11992. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11993. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11994. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11995. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11996. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11997. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11998. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11999. }
  12000. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12001. const container = document.getElementById('dhcp-network-modal-options-list');
  12002. if (!container) return;
  12003. container.innerHTML = '';
  12004. const opts = state.dhcpOptions || [];
  12005. if (opts.length === 0) {
  12006. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12007. return;
  12008. }
  12009. opts.forEach(o => {
  12010. const isChecked = selectedIds.includes(o.id);
  12011. const label = document.createElement('label');
  12012. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12013. label.innerHTML = `
  12014. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12015. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12016. `;
  12017. container.appendChild(label);
  12018. });
  12019. }
  12020. function closeDHCPNetworkModal() {
  12021. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12022. }
  12023. async function submitSaveDHCPNetwork(e) {
  12024. e.preventDefault();
  12025. const id = document.getElementById('dhcp-network-modal-id').value;
  12026. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12027. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12028. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12029. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12030. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  12031. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  12032. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  12033. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  12034. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12035. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12036. const selectedOpts = [];
  12037. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12038. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12039. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12040. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12041. try {
  12042. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12043. method: 'POST',
  12044. headers: { 'Content-Type': 'application/json' },
  12045. body: JSON.stringify({
  12046. id,
  12047. address,
  12048. gateway,
  12049. netmask,
  12050. dns_servers: dnsServers,
  12051. domain,
  12052. ntp_servers: ntpServers,
  12053. next_server: tftp,
  12054. boot_file_name: bootfile,
  12055. wins_servers: winsServers,
  12056. dhcp_options: selectedOpts,
  12057. comment
  12058. })
  12059. });
  12060. if (res.ok) {
  12061. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12062. closeDHCPNetworkModal();
  12063. loadDHCPServer(false);
  12064. fetchData(false);
  12065. } else {
  12066. const err = await res.text();
  12067. showToast('Error', err, 'error');
  12068. }
  12069. } catch (err) {
  12070. showToast('Error', err.message, 'error');
  12071. }
  12072. }
  12073. async function deleteDHCPNetwork(id, addr) {
  12074. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12075. try {
  12076. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12077. if (res.ok) {
  12078. showToast('Deleted', `Network ${addr} removed`, 'success');
  12079. loadDHCPServer(false);
  12080. fetchData(false);
  12081. }
  12082. } catch (err) {
  12083. showToast('Error', err.message, 'error');
  12084. }
  12085. }
  12086. // ==================== MODALS & ACTIONS: LEASES ====================
  12087. function openAddDHCPStaticLeaseModal() {
  12088. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12089. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12090. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12091. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12092. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12093. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12094. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12095. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12096. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12097. }
  12098. function closeDHCPStaticLeaseModal() {
  12099. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12100. }
  12101. async function submitSaveDHCPStaticLease(e) {
  12102. e.preventDefault();
  12103. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12104. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12105. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12106. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12107. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12108. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12109. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12110. try {
  12111. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12112. method: 'POST',
  12113. headers: { 'Content-Type': 'application/json' },
  12114. body: JSON.stringify({
  12115. id,
  12116. mac_address: mac,
  12117. address: ip,
  12118. hostname,
  12119. server,
  12120. comment,
  12121. disabled
  12122. })
  12123. });
  12124. if (res.ok) {
  12125. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12126. closeDHCPStaticLeaseModal();
  12127. loadDHCPServer(false);
  12128. fetchData(false);
  12129. } else {
  12130. const err = await res.text();
  12131. showToast('Error', err, 'error');
  12132. }
  12133. } catch (err) {
  12134. showToast('Error', err.message, 'error');
  12135. }
  12136. }
  12137. async function deleteDHCPStaticLease(id) {
  12138. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12139. try {
  12140. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12141. if (res.ok) {
  12142. showToast('Deleted', 'Static lease removed', 'success');
  12143. loadDHCPServer(false);
  12144. fetchData(false);
  12145. }
  12146. } catch (err) {
  12147. showToast('Error', err.message, 'error');
  12148. }
  12149. }
  12150. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12151. try {
  12152. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12153. method: 'POST',
  12154. headers: { 'Content-Type': 'application/json' },
  12155. body: JSON.stringify({
  12156. mac_address: mac,
  12157. address: ip,
  12158. hostname,
  12159. comment: comment || 'Converted to static'
  12160. })
  12161. });
  12162. if (res.ok) {
  12163. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12164. loadDHCPServer(false);
  12165. fetchData(false);
  12166. } else {
  12167. const err = await res.text();
  12168. showToast('Error', err, 'error');
  12169. }
  12170. } catch (err) {
  12171. showToast('Error', err.message, 'error');
  12172. }
  12173. }
  12174. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12175. function openAddDHCPOptionModal() {
  12176. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12177. document.getElementById('dhcp-option-modal-id').value = '';
  12178. document.getElementById('dhcp-option-modal-name').value = '';
  12179. document.getElementById('dhcp-option-modal-code').value = '';
  12180. document.getElementById('dhcp-option-modal-value').value = '';
  12181. document.getElementById('dhcp-option-modal-comment').value = '';
  12182. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12183. }
  12184. function openEditDHCPOptionModal(id) {
  12185. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12186. if (!o) return;
  12187. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12188. document.getElementById('dhcp-option-modal-id').value = o.id;
  12189. document.getElementById('dhcp-option-modal-name').value = o.name;
  12190. document.getElementById('dhcp-option-modal-code').value = o.code;
  12191. document.getElementById('dhcp-option-modal-value').value = o.value;
  12192. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12193. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12194. }
  12195. function closeDHCPOptionModal() {
  12196. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12197. }
  12198. async function submitSaveDHCPOption(e) {
  12199. e.preventDefault();
  12200. const id = document.getElementById('dhcp-option-modal-id').value;
  12201. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12202. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12203. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12204. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12205. try {
  12206. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12207. method: 'POST',
  12208. headers: { 'Content-Type': 'application/json' },
  12209. body: JSON.stringify({ id, name, code, value, comment })
  12210. });
  12211. if (res.ok) {
  12212. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12213. closeDHCPOptionModal();
  12214. loadDHCPServer(false);
  12215. fetchData(false);
  12216. } else {
  12217. const err = await res.text();
  12218. showToast('Error', err, 'error');
  12219. }
  12220. } catch (err) {
  12221. showToast('Error', err.message, 'error');
  12222. }
  12223. }
  12224. async function deleteDHCPOption(id, name) {
  12225. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12226. try {
  12227. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12228. if (res.ok) {
  12229. showToast('Deleted', `Option ${name} removed`, 'success');
  12230. loadDHCPServer(false);
  12231. fetchData(false);
  12232. }
  12233. } catch (err) {
  12234. showToast('Error', err.message, 'error');
  12235. }
  12236. }
  12237. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12238. function openDHCPServerSetupModal() {
  12239. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12240. onDHCPWizardIfaceChange();
  12241. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12242. }
  12243. function closeDHCPServerSetupModal() {
  12244. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12245. }
  12246. function onDHCPWizardIfaceChange() {
  12247. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12248. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12249. let ip = '192.168.88.1';
  12250. let prefix = '24';
  12251. if (iface && iface.ip_address) {
  12252. const parts = iface.ip_address.split('/');
  12253. ip = parts[0];
  12254. if (parts.length > 1) prefix = parts[1];
  12255. }
  12256. // Calculate subnet base (e.g. 192.168.88.0/24)
  12257. const ipParts = ip.split('.');
  12258. if (ipParts.length === 4) {
  12259. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12260. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12261. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12262. document.getElementById('dhcp-wizard-gateway').value = ip;
  12263. document.getElementById('dhcp-wizard-pool').value = pool;
  12264. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12265. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12266. }
  12267. }
  12268. async function submitDHCPServerSetupWizard(e) {
  12269. e.preventDefault();
  12270. const iface = document.getElementById('dhcp-wizard-iface').value;
  12271. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12272. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12273. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12274. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12275. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12276. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12277. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12278. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12279. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12280. try {
  12281. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12282. method: 'POST',
  12283. headers: { 'Content-Type': 'application/json' },
  12284. body: JSON.stringify({
  12285. interface: iface,
  12286. address_space: space,
  12287. gateway: gw,
  12288. address_pool: pool,
  12289. dns_servers: dnsServers,
  12290. lease_time: leaseTime,
  12291. ntp_servers: ntpServers,
  12292. next_server: tftp
  12293. })
  12294. });
  12295. if (res.ok) {
  12296. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12297. closeDHCPServerSetupModal();
  12298. loadDHCPServer(false);
  12299. fetchData(false);
  12300. } else {
  12301. const err = await res.text();
  12302. showToast('Error', err, 'error');
  12303. }
  12304. } catch (err) {
  12305. showToast('Error', err.message, 'error');
  12306. }
  12307. }
  12308. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12309. const sel = document.getElementById(elemId);
  12310. if (!sel) return;
  12311. sel.innerHTML = '<option value="">Select interface...</option>';
  12312. const ifaces = state.interfaces || [];
  12313. ifaces.forEach(i => {
  12314. if (i.name === 'lo') return;
  12315. const opt = document.createElement('option');
  12316. opt.value = i.name;
  12317. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12318. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12319. if (i.name === selectedVal) opt.selected = true;
  12320. sel.appendChild(opt);
  12321. });
  12322. }
  12323. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12324. function initTableSorting() {
  12325. document.querySelectorAll('table').forEach(setupSortableTable);
  12326. }
  12327. function setupSortableTable(table) {
  12328. const thead = table.querySelector('thead');
  12329. const tbody = table.querySelector('tbody');
  12330. if (!thead || !tbody) return;
  12331. const headerRows = thead.querySelectorAll('tr');
  12332. if (headerRows.length === 0) return;
  12333. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12334. ths.forEach((th, colIdx) => {
  12335. if (th._sortBound) return;
  12336. th._sortBound = true;
  12337. const rawText = th.innerText.trim().toLowerCase();
  12338. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12339. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12340. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12341. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12342. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12343. return;
  12344. }
  12345. th.classList.add('table-sortable', 'group');
  12346. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12347. let icon = th.querySelector('.table-sort-icon');
  12348. if (!icon) {
  12349. icon = document.createElement('span');
  12350. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12351. icon.innerHTML = '⇅';
  12352. th.appendChild(icon);
  12353. }
  12354. th.addEventListener('click', (e) => {
  12355. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12356. handleHeaderClick(table, th, colIdx);
  12357. });
  12358. });
  12359. if (!tbody._sortObserved) {
  12360. tbody._sortObserved = true;
  12361. let sortDebounceTimer = null;
  12362. const observer = new MutationObserver((mutations) => {
  12363. if (tbody._isSorting) return;
  12364. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12365. if (!hasChildChanges) return;
  12366. clearTimeout(sortDebounceTimer);
  12367. sortDebounceTimer = setTimeout(() => {
  12368. if (tbody._isSorting) return;
  12369. if (table._activeSort && table._activeSort.dir !== 'none') {
  12370. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12371. } else {
  12372. tagOriginalRowOrder(tbody);
  12373. }
  12374. }, 10);
  12375. });
  12376. observer.observe(tbody, { childList: true });
  12377. }
  12378. tagOriginalRowOrder(tbody);
  12379. }
  12380. function tagOriginalRowOrder(tbody) {
  12381. let idx = 0;
  12382. Array.from(tbody.children).forEach(tr => {
  12383. if (!tr.querySelector('td[colspan]')) {
  12384. if (!tr.hasAttribute('data-orig-idx')) {
  12385. tr.setAttribute('data-orig-idx', idx++);
  12386. }
  12387. }
  12388. });
  12389. }
  12390. function handleHeaderClick(table, th, colIdx) {
  12391. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12392. let newDir = 'asc';
  12393. if (currentSort.colIdx === colIdx) {
  12394. if (currentSort.dir === 'asc') newDir = 'desc';
  12395. else if (currentSort.dir === 'desc') newDir = 'none';
  12396. else newDir = 'asc';
  12397. } else {
  12398. newDir = 'asc';
  12399. }
  12400. table._activeSort = { colIdx, dir: newDir };
  12401. updateHeaderIcons(table, colIdx, newDir);
  12402. applyTableSort(table, colIdx, newDir, true);
  12403. }
  12404. function updateHeaderIcons(table, activeColIdx, dir) {
  12405. const thead = table.querySelector('thead');
  12406. if (!thead) return;
  12407. const ths = thead.querySelectorAll('th');
  12408. ths.forEach((th, idx) => {
  12409. const icon = th.querySelector('.table-sort-icon');
  12410. if (!icon) return;
  12411. if (idx === activeColIdx && dir !== 'none') {
  12412. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12413. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12414. th.classList.add('table-sorted-active');
  12415. } else {
  12416. icon.innerHTML = '⇅';
  12417. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12418. th.classList.remove('table-sorted-active');
  12419. }
  12420. });
  12421. }
  12422. function applyTableSort(table, colIdx, dir, userInitiated) {
  12423. const tbody = table.querySelector('tbody');
  12424. if (!tbody || tbody.children.length <= 1) return;
  12425. tbody._isSorting = true;
  12426. tagOriginalRowOrder(tbody);
  12427. // Group parent rows and any attached drawer/sub-rows
  12428. const groups = [];
  12429. let currentGroup = null;
  12430. Array.from(tbody.children).forEach(tr => {
  12431. if (tr.querySelector('td[colspan]')) {
  12432. if (currentGroup) {
  12433. currentGroup.subRows.push(tr);
  12434. } else {
  12435. groups.push({ mainRow: tr, subRows: [] });
  12436. }
  12437. } else {
  12438. currentGroup = { mainRow: tr, subRows: [] };
  12439. groups.push(currentGroup);
  12440. }
  12441. });
  12442. if (dir === 'none') {
  12443. groups.sort((a, b) => {
  12444. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12445. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12446. return idxA - idxB;
  12447. });
  12448. } else {
  12449. groups.sort((a, b) => {
  12450. const cellA = a.mainRow.children[colIdx];
  12451. const cellB = b.mainRow.children[colIdx];
  12452. const res = compareTableCells(cellA, cellB);
  12453. return dir === 'asc' ? res : -res;
  12454. });
  12455. }
  12456. // Re-append rows in sorted order
  12457. groups.forEach(g => {
  12458. tbody.appendChild(g.mainRow);
  12459. g.subRows.forEach(sub => tbody.appendChild(sub));
  12460. });
  12461. tbody._isSorting = false;
  12462. }
  12463. function getCellRawText(cell) {
  12464. if (!cell) return '';
  12465. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12466. const input = cell.querySelector('input, select');
  12467. if (input) {
  12468. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12469. return input.value;
  12470. }
  12471. return cell.innerText.trim();
  12472. }
  12473. function parseTrafficToNumber(str) {
  12474. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12475. if (!m) return null;
  12476. const num = parseFloat(m[1].replace(/,/g, ''));
  12477. if (isNaN(num)) return null;
  12478. const unit = m[2].toUpperCase();
  12479. let mult = 1;
  12480. if (unit.startsWith('K')) mult = 1024;
  12481. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12482. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12483. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12484. return num * mult;
  12485. }
  12486. function parseIpToNumber(str) {
  12487. const clean = str.replace(/^[!~]/, '').trim();
  12488. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12489. if (!m) return null;
  12490. const o1 = parseInt(m[1], 10);
  12491. const o2 = parseInt(m[2], 10);
  12492. const o3 = parseInt(m[3], 10);
  12493. const o4 = parseInt(m[4], 10);
  12494. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12495. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12496. }
  12497. function parseCompoundPackets(str) {
  12498. const m = str.match(/^([\d,]+)p/);
  12499. if (!m) return null;
  12500. return parseInt(m[1].replace(/,/g, ''), 10);
  12501. }
  12502. function compareTableCells(cellA, cellB) {
  12503. const a = getCellRawText(cellA);
  12504. const b = getCellRawText(cellB);
  12505. if (a === '' && b !== '') return 1;
  12506. if (b === '' && a !== '') return -1;
  12507. if (a === b) return 0;
  12508. // 1. IP Addresses / CIDR
  12509. const ipA = parseIpToNumber(a);
  12510. const ipB = parseIpToNumber(b);
  12511. if (ipA !== null && ipB !== null) return ipA - ipB;
  12512. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12513. const pktA = parseCompoundPackets(a);
  12514. const pktB = parseCompoundPackets(b);
  12515. if (pktA !== null && pktB !== null) return pktA - pktB;
  12516. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12517. const trafA = parseTrafficToNumber(a);
  12518. const trafB = parseTrafficToNumber(b);
  12519. if (trafA !== null && trafB !== null) return trafA - trafB;
  12520. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12521. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12522. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12523. const numA = Number(cleanNumA);
  12524. const numB = Number(cleanNumB);
  12525. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12526. return numA - numB;
  12527. }
  12528. // 5. Natural case-insensitive string compare
  12529. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12530. }
  12531. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12532. async function loadVRRP(showToastNotification = false) {
  12533. try {
  12534. const [instRes, sumRes] = await Promise.all([
  12535. fetch(`${API_BASE}/vrrp/instances`),
  12536. fetch(`${API_BASE}/vrrp/summary`)
  12537. ]);
  12538. if (instRes.ok) {
  12539. state.vrrpInstances = await instRes.json();
  12540. renderVRRP();
  12541. }
  12542. if (sumRes.ok) {
  12543. state.vrrpSummary = await sumRes.json();
  12544. renderVRRPSummary();
  12545. }
  12546. if (showToastNotification) {
  12547. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12548. }
  12549. } catch (err) {
  12550. console.error('Failed to load VRRP:', err);
  12551. }
  12552. }
  12553. function renderVRRPSummary() {
  12554. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12555. const elTotal = document.getElementById('vrrp-stat-total');
  12556. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12557. const elMaster = document.getElementById('vrrp-stat-master');
  12558. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12559. const elBackup = document.getElementById('vrrp-stat-backup');
  12560. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12561. const bCount = document.getElementById('badge-vrrp-count');
  12562. if (bCount) bCount.innerText = s.total_instances || 0;
  12563. const dot = document.getElementById('badge-vrrp-dot');
  12564. if (dot) {
  12565. if (s.master_instances > 0) {
  12566. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12567. } else if (s.backup_instances > 0) {
  12568. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12569. } else {
  12570. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12571. }
  12572. }
  12573. }
  12574. function renderVRRP() {
  12575. const tbody = document.getElementById('vrrp-table-tbody');
  12576. const empty = document.getElementById('vrrp-table-empty');
  12577. if (!tbody) return;
  12578. tbody.innerHTML = '';
  12579. const instances = state.vrrpInstances || [];
  12580. if (instances.length === 0) {
  12581. empty?.classList.remove('hidden');
  12582. return;
  12583. }
  12584. empty?.classList.add('hidden');
  12585. instances.forEach(inst => {
  12586. const tr = document.createElement('tr');
  12587. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12588. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12589. 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>`;
  12590. if (inst.disabled) {
  12591. 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>`;
  12592. } else if (inst.state === 'MASTER') {
  12593. 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>`;
  12594. } else if (inst.state === 'BACKUP') {
  12595. 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>`;
  12596. } else if (inst.state === 'FAULT') {
  12597. 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>`;
  12598. }
  12599. // Render State Badge
  12600. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12601. if (!inst.disabled) {
  12602. if (inst.state === 'MASTER') {
  12603. 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>`;
  12604. } else if (inst.state === 'BACKUP') {
  12605. 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>`;
  12606. } else if (inst.state === 'FAULT') {
  12607. 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>`;
  12608. }
  12609. }
  12610. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12611. tr.innerHTML = `
  12612. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12613. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12614. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12615. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12616. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12617. <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>
  12618. <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>
  12619. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12620. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12621. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12622. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12623. <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>
  12624. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12625. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12626. </td>
  12627. `;
  12628. tbody.appendChild(tr);
  12629. });
  12630. }
  12631. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12632. const sel = document.getElementById(elemId);
  12633. if (!sel) return;
  12634. sel.innerHTML = '<option value="">Select interface...</option>';
  12635. const ifaces = state.interfaces || [];
  12636. ifaces.forEach(i => {
  12637. const opt = document.createElement('option');
  12638. opt.value = i.name;
  12639. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12640. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12641. sel.appendChild(opt);
  12642. });
  12643. }
  12644. function openAddVRRPModal() {
  12645. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12646. document.getElementById('modal-vrrp-id').value = '';
  12647. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12648. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12649. document.getElementById('modal-vrrp-priority').value = 100;
  12650. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12651. document.getElementById('modal-vrrp-version').value = '3';
  12652. document.getElementById('modal-vrrp-interval').value = 1;
  12653. document.getElementById('modal-vrrp-authtype').value = 'none';
  12654. document.getElementById('modal-vrrp-authpass').value = '';
  12655. document.getElementById('modal-vrrp-comment').value = '';
  12656. document.getElementById('modal-vrrp-preempt').checked = true;
  12657. document.getElementById('modal-vrrp-disabled').checked = false;
  12658. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12659. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12660. }
  12661. function openEditVRRPModal(id) {
  12662. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12663. if (!inst) return;
  12664. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12665. document.getElementById('modal-vrrp-id').value = inst.id;
  12666. document.getElementById('modal-vrrp-name').value = inst.name;
  12667. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12668. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12669. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12670. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12671. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12672. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12673. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12674. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12675. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12676. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12677. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12678. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12679. }
  12680. function closeVRRPModal() {
  12681. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12682. }
  12683. async function submitSaveVRRP(e) {
  12684. e.preventDefault();
  12685. const id = document.getElementById('modal-vrrp-id').value;
  12686. const name = document.getElementById('modal-vrrp-name').value.trim();
  12687. const iface = document.getElementById('modal-vrrp-iface').value;
  12688. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12689. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12690. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12691. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12692. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12693. const authType = document.getElementById('modal-vrrp-authtype').value;
  12694. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12695. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12696. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12697. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12698. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12699. try {
  12700. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12701. method: 'POST',
  12702. headers: { 'Content-Type': 'application/json' },
  12703. body: JSON.stringify({
  12704. id,
  12705. name,
  12706. interface: iface,
  12707. vrid,
  12708. priority,
  12709. virtual_ips: vips,
  12710. version,
  12711. interval,
  12712. auth_type: authType,
  12713. auth_password: authPass,
  12714. comment,
  12715. preempt,
  12716. disabled
  12717. })
  12718. });
  12719. if (res.ok) {
  12720. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12721. closeVRRPModal();
  12722. loadVRRP(false);
  12723. fetchData(false);
  12724. } else {
  12725. const err = await res.text();
  12726. showToast('Error', err, 'error');
  12727. }
  12728. } catch (err) {
  12729. showToast('Error', err.message, 'error');
  12730. }
  12731. }
  12732. async function deleteVRRP(id, name) {
  12733. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12734. try {
  12735. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12736. if (res.ok) {
  12737. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12738. loadVRRP(false);
  12739. fetchData(false);
  12740. } else {
  12741. const err = await res.text();
  12742. showToast('Error', err, 'error');
  12743. }
  12744. } catch (err) {
  12745. showToast('Error', err.message, 'error');
  12746. }
  12747. }
  12748. async function toggleVRRPState(id, disabled) {
  12749. try {
  12750. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12751. method: 'POST',
  12752. headers: { 'Content-Type': 'application/json' },
  12753. body: JSON.stringify({ disabled })
  12754. });
  12755. if (res.ok) {
  12756. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12757. loadVRRP(false);
  12758. fetchData(false);
  12759. } else {
  12760. const err = await res.text();
  12761. showToast('Error', err, 'error');
  12762. }
  12763. } catch (err) {
  12764. showToast('Error', err.message, 'error');
  12765. }
  12766. }
  12767. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12768. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12769. const docTableObserver = new MutationObserver((mutations) => {
  12770. let needsInit = false;
  12771. for (const m of mutations) {
  12772. for (const node of m.addedNodes) {
  12773. if (node.nodeType === 1) {
  12774. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12775. needsInit = true;
  12776. break;
  12777. }
  12778. }
  12779. }
  12780. if (needsInit) break;
  12781. }
  12782. if (needsInit) {
  12783. initTableSorting();
  12784. }
  12785. });
  12786. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12787. }
  12788. // =========================================================================
  12789. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  12790. // =========================================================================
  12791. const bwtestState = {
  12792. running: false,
  12793. pollTimer: null,
  12794. eventSource: null,
  12795. chartPoints: [],
  12796. maxChartPoints: 60,
  12797. serverConfig: null,
  12798. peakTx: 0,
  12799. peakRx: 0,
  12800. targetDuration: 10,
  12801. lastSampleIndex: 0
  12802. };
  12803. async function loadBwTestView() {
  12804. fetchBwTestServerStatus();
  12805. loadBwTestHistory();
  12806. resizeBwTestCanvas();
  12807. checkActiveBwTest();
  12808. }
  12809. async function fetchBwTestServerStatus() {
  12810. try {
  12811. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  12812. if (!res.ok) return;
  12813. const s = await res.json();
  12814. bwtestState.serverConfig = s;
  12815. // Update indicator and badges
  12816. const indicator = document.getElementById('bwtest-server-indicator');
  12817. const badge = document.getElementById('bwtest-server-badge');
  12818. const sideBadge = document.getElementById('badge-bwtest-server');
  12819. if (s.enabled && s.running) {
  12820. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12821. if (badge) {
  12822. badge.innerText = `Port ${s.port} (Active)`;
  12823. badge.className = 'text-emerald-400 font-bold';
  12824. }
  12825. if (sideBadge) {
  12826. sideBadge.innerText = s.port;
  12827. 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';
  12828. }
  12829. } else {
  12830. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  12831. if (badge) {
  12832. badge.innerText = `Disabled`;
  12833. badge.className = 'text-slate-500 font-bold';
  12834. }
  12835. if (sideBadge) {
  12836. sideBadge.innerText = 'Off';
  12837. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  12838. }
  12839. }
  12840. // Modal fields
  12841. const toggle = document.getElementById('bwtest-server-enable-toggle');
  12842. if (toggle) toggle.checked = !!s.enabled;
  12843. const portInp = document.getElementById('bwtest-server-port-input');
  12844. if (portInp) portInp.value = s.port || 2000;
  12845. const actSess = document.getElementById('bwtest-modal-active-sessions');
  12846. if (actSess) actSess.innerText = s.active_sessions || 0;
  12847. const totServ = document.getElementById('bwtest-modal-total-served');
  12848. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  12849. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  12850. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  12851. } catch (err) {
  12852. console.error('Failed to fetch BwTest server status:', err);
  12853. }
  12854. }
  12855. function openBwTestServerModal() {
  12856. fetchBwTestServerStatus();
  12857. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  12858. }
  12859. function closeBwTestServerModal() {
  12860. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  12861. }
  12862. async function submitBwTestServerSettings(e) {
  12863. e.preventDefault();
  12864. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  12865. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  12866. try {
  12867. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  12868. method: 'POST',
  12869. headers: { 'Content-Type': 'application/json' },
  12870. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  12871. });
  12872. if (!res.ok) {
  12873. const err = await res.json();
  12874. throw new Error(err.error || 'Failed to update server configuration');
  12875. }
  12876. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  12877. closeBwTestServerModal();
  12878. fetchBwTestServerStatus();
  12879. } catch (err) {
  12880. showToast('Server Configuration Error', err.message, 'error');
  12881. }
  12882. }
  12883. function setBwTestTarget(target) {
  12884. const inp = document.getElementById('bwtest-input-target');
  12885. if (inp) inp.value = target;
  12886. }
  12887. function setBwTestProtocol(proto) {
  12888. const hiddenInp = document.getElementById('bwtest-input-protocol');
  12889. if (hiddenInp) hiddenInp.value = proto;
  12890. const btnUdp = document.getElementById('bwtest-proto-udp');
  12891. const btnTcp = document.getElementById('bwtest-proto-tcp');
  12892. const badge = document.getElementById('bwtest-proto-badge');
  12893. const pktField = document.getElementById('bwtest-field-pktsize');
  12894. 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';
  12895. 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';
  12896. 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';
  12897. if (proto === 'udp') {
  12898. if (btnUdp) {
  12899. btnUdp.className = activeUdpCls;
  12900. const dot = btnUdp.querySelector('span');
  12901. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  12902. }
  12903. if (btnTcp) {
  12904. btnTcp.className = inactiveCls;
  12905. const dot = btnTcp.querySelector('span');
  12906. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12907. }
  12908. if (badge) {
  12909. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  12910. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  12911. }
  12912. if (pktField) pktField.classList.remove('opacity-40');
  12913. } else {
  12914. if (btnUdp) {
  12915. btnUdp.className = inactiveCls;
  12916. const dot = btnUdp.querySelector('span');
  12917. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12918. }
  12919. if (btnTcp) {
  12920. btnTcp.className = activeTcpCls;
  12921. const dot = btnTcp.querySelector('span');
  12922. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  12923. }
  12924. if (badge) {
  12925. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  12926. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  12927. }
  12928. if (pktField) pktField.classList.add('opacity-40');
  12929. }
  12930. }
  12931. function setBwTestDirection(dir) {
  12932. const hiddenInp = document.getElementById('bwtest-input-direction');
  12933. if (hiddenInp) hiddenInp.value = dir;
  12934. const btnBoth = document.getElementById('bwtest-dir-both');
  12935. const btnTx = document.getElementById('bwtest-dir-tx');
  12936. const btnRx = document.getElementById('bwtest-dir-rx');
  12937. 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';
  12938. 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';
  12939. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  12940. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  12941. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  12942. }
  12943. function setBwTestLimit(bps) {
  12944. const sel = document.getElementById('bwtest-input-limit');
  12945. if (sel) sel.value = String(bps);
  12946. }
  12947. async function checkActiveBwTest() {
  12948. try {
  12949. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  12950. if (!res.ok) return;
  12951. const st = await res.json();
  12952. if (st.running) {
  12953. setBwTestRunningUI(true);
  12954. if (st.current_sample) handleBwTestSample(st.current_sample);
  12955. startBwTestTelemetry();
  12956. }
  12957. } catch (err) {
  12958. console.error('Failed to check active BwTest:', err);
  12959. }
  12960. }
  12961. async function startBwTest(e) {
  12962. if (e && e.preventDefault) e.preventDefault();
  12963. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  12964. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  12965. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  12966. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  12967. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  12968. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  12969. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  12970. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  12971. bwtestState.targetDuration = duration;
  12972. bwtestState.chartPoints = [];
  12973. bwtestState.peakTx = 0;
  12974. bwtestState.peakRx = 0;
  12975. bwtestState.lastSampleIndex = 0;
  12976. // Clear UI elements
  12977. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  12978. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  12979. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  12980. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  12981. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  12982. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  12983. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  12984. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  12985. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  12986. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  12987. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  12988. const tbody = document.getElementById('bwtest-samples-tbody');
  12989. if (tbody) tbody.innerHTML = '';
  12990. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  12991. setBwTestRunningUI(true);
  12992. try {
  12993. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  12994. method: 'POST',
  12995. headers: { 'Content-Type': 'application/json' },
  12996. body: JSON.stringify({
  12997. target,
  12998. port,
  12999. direction,
  13000. protocol,
  13001. bandwidth_limit,
  13002. packet_size,
  13003. streams,
  13004. duration
  13005. })
  13006. });
  13007. if (!res.ok) {
  13008. const err = await res.json();
  13009. throw new Error(err.error || 'Failed to start bandwidth test');
  13010. }
  13011. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13012. startBwTestTelemetry();
  13013. } catch (err) {
  13014. setBwTestRunningUI(false);
  13015. showToast('Start Failed', err.message, 'error');
  13016. }
  13017. }
  13018. function setBwTestRunningUI(running) {
  13019. bwtestState.running = running;
  13020. const startBtn = document.getElementById('bwtest-btn-start');
  13021. const stopBtn = document.getElementById('bwtest-btn-stop');
  13022. const badge = document.getElementById('bwtest-run-status-badge');
  13023. const ph = document.getElementById('bwtest-chart-placeholder');
  13024. if (running) {
  13025. if (startBtn) {
  13026. startBtn.disabled = true;
  13027. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13028. }
  13029. if (stopBtn) {
  13030. stopBtn.disabled = false;
  13031. stopBtn.classList.remove('opacity-40');
  13032. }
  13033. if (badge) {
  13034. badge.innerText = 'TESTING...';
  13035. 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';
  13036. }
  13037. if (ph) ph.style.display = 'none';
  13038. } else {
  13039. if (startBtn) {
  13040. startBtn.disabled = false;
  13041. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13042. }
  13043. if (stopBtn) {
  13044. stopBtn.disabled = true;
  13045. stopBtn.classList.add('opacity-40');
  13046. }
  13047. if (badge) {
  13048. badge.innerText = 'IDLE';
  13049. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13050. }
  13051. }
  13052. }
  13053. async function stopBwTest() {
  13054. try {
  13055. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13056. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13057. } catch (err) {
  13058. console.error('Failed to stop test:', err);
  13059. }
  13060. }
  13061. function startBwTestTelemetry() {
  13062. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13063. bwtestState.pollTimer = setInterval(async () => {
  13064. try {
  13065. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13066. if (!res.ok) return;
  13067. const st = await res.json();
  13068. if (st.recent_samples && st.recent_samples.length > 0) {
  13069. // Process new samples
  13070. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13071. newSamples.forEach(s => handleBwTestSample(s));
  13072. bwtestState.lastSampleIndex = st.recent_samples.length;
  13073. }
  13074. if (!st.running) {
  13075. clearInterval(bwtestState.pollTimer);
  13076. bwtestState.pollTimer = null;
  13077. setBwTestRunningUI(false);
  13078. handleBwTestFinish(st.summary, st.error);
  13079. }
  13080. } catch (err) {
  13081. console.error('BwTest polling error:', err);
  13082. }
  13083. }, 400);
  13084. }
  13085. function handleBwTestSample(s) {
  13086. if (!s) return;
  13087. const txMbps = s.tx_mbps || 0;
  13088. const rxMbps = s.rx_mbps || 0;
  13089. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13090. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13091. // KPI updates
  13092. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13093. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13094. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13095. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13096. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13097. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13098. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13099. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13100. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13101. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13102. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13103. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13104. const elLoss = document.getElementById('bwtest-stat-loss');
  13105. if (elLoss) {
  13106. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13107. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13108. }
  13109. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13110. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13111. const elJitter = document.getElementById('bwtest-stat-jitter');
  13112. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13113. const elTime = document.getElementById('bwtest-stat-time');
  13114. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13115. const elData = document.getElementById('bwtest-stat-data');
  13116. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13117. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13118. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13119. // Append point to chart buffer
  13120. bwtestState.chartPoints.push({
  13121. elapsed: s.elapsed_sec || 0,
  13122. tx: txMbps,
  13123. rx: rxMbps
  13124. });
  13125. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13126. bwtestState.chartPoints.shift();
  13127. }
  13128. drawBwTestChart();
  13129. // Add row to breakdown table
  13130. const tbody = document.getElementById('bwtest-samples-tbody');
  13131. if (tbody) {
  13132. const tr = document.createElement('tr');
  13133. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13134. tr.innerHTML = `
  13135. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13136. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13137. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13138. <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>
  13139. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13140. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13141. `;
  13142. tbody.insertBefore(tr, tbody.firstChild);
  13143. const countEl = document.getElementById('bwtest-sample-count');
  13144. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13145. }
  13146. }
  13147. function handleBwTestFinish(summary, error) {
  13148. const badge = document.getElementById('bwtest-run-status-badge');
  13149. if (error) {
  13150. showToast('Benchmark Error', error, 'error');
  13151. if (badge) {
  13152. badge.innerText = 'ERROR';
  13153. 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';
  13154. }
  13155. } else if (summary) {
  13156. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13157. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13158. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13159. if (badge) {
  13160. badge.innerText = 'COMPLETED';
  13161. 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';
  13162. }
  13163. }
  13164. loadBwTestHistory();
  13165. fetchBwTestServerStatus();
  13166. }
  13167. function resizeBwTestCanvas() {
  13168. const canvas = document.getElementById('bwtest-chart');
  13169. if (!canvas || !canvas.parentElement) return;
  13170. const rect = canvas.parentElement.getBoundingClientRect();
  13171. const dpr = window.devicePixelRatio || 1;
  13172. canvas.width = rect.width * dpr;
  13173. canvas.height = rect.height * dpr;
  13174. const ctx = canvas.getContext('2d');
  13175. ctx.scale(dpr, dpr);
  13176. drawBwTestChart();
  13177. }
  13178. window.addEventListener('resize', () => {
  13179. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13180. });
  13181. function drawBwTestChart() {
  13182. const canvas = document.getElementById('bwtest-chart');
  13183. if (!canvas) return;
  13184. const ctx = canvas.getContext('2d');
  13185. const dpr = window.devicePixelRatio || 1;
  13186. const width = canvas.width / dpr;
  13187. const height = canvas.height / dpr;
  13188. ctx.clearRect(0, 0, width, height);
  13189. const points = bwtestState.chartPoints;
  13190. if (!points || points.length === 0) return;
  13191. // Determine scale ceiling
  13192. let maxRate = 10;
  13193. for (const p of points) {
  13194. if (p.tx > maxRate) maxRate = p.tx;
  13195. if (p.rx > maxRate) maxRate = p.rx;
  13196. }
  13197. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13198. const paddingLeft = 55;
  13199. const paddingBottom = 24;
  13200. const paddingTop = 12;
  13201. const paddingRight = 16;
  13202. const chartW = width - paddingLeft - paddingRight;
  13203. const chartH = height - paddingTop - paddingBottom;
  13204. // Grid Lines and Y-Axis labels
  13205. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13206. ctx.lineWidth = 1;
  13207. ctx.fillStyle = '#94a3b8';
  13208. ctx.font = '10px monospace';
  13209. ctx.textAlign = 'right';
  13210. const gridSteps = 4;
  13211. for (let i = 0; i <= gridSteps; i++) {
  13212. const val = (maxRate / gridSteps) * i;
  13213. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13214. ctx.beginPath();
  13215. ctx.moveTo(paddingLeft, y);
  13216. ctx.lineTo(width - paddingRight, y);
  13217. ctx.stroke();
  13218. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13219. }
  13220. // Draw TX Line (Cyan #22d3ee)
  13221. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13222. // Draw RX Line (Purple #a855f7)
  13223. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13224. }
  13225. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13226. if (points.length < 2) return;
  13227. const stepX = w / Math.max(points.length - 1, 1);
  13228. // Gradient area fill
  13229. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13230. grad.addColorStop(0, fillColor);
  13231. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13232. ctx.beginPath();
  13233. points.forEach((p, idx) => {
  13234. const x = left + idx * stepX;
  13235. const val = valFn(p);
  13236. const y = top + h - (val / maxVal) * h;
  13237. if (idx === 0) {
  13238. ctx.moveTo(x, y);
  13239. } else {
  13240. ctx.lineTo(x, y);
  13241. }
  13242. });
  13243. // Complete path for fill
  13244. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13245. ctx.lineTo(left, top + h);
  13246. ctx.closePath();
  13247. ctx.fillStyle = grad;
  13248. ctx.fill();
  13249. // Draw line stroke
  13250. ctx.beginPath();
  13251. ctx.lineWidth = 2.5;
  13252. ctx.strokeStyle = strokeColor;
  13253. points.forEach((p, idx) => {
  13254. const x = left + idx * stepX;
  13255. const val = valFn(p);
  13256. const y = top + h - (val / maxVal) * h;
  13257. if (idx === 0) {
  13258. ctx.moveTo(x, y);
  13259. } else {
  13260. ctx.lineTo(x, y);
  13261. }
  13262. });
  13263. ctx.stroke();
  13264. // Draw end point halo
  13265. const lastP = points[points.length - 1];
  13266. const lastX = left + (points.length - 1) * stepX;
  13267. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13268. ctx.fillStyle = strokeColor;
  13269. ctx.beginPath();
  13270. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13271. ctx.fill();
  13272. }
  13273. async function loadBwTestHistory() {
  13274. try {
  13275. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13276. if (!res.ok) return;
  13277. const list = await res.json();
  13278. renderBwTestHistory(Array.isArray(list) ? list : []);
  13279. } catch (err) {
  13280. console.error('Failed to load BwTest history:', err);
  13281. }
  13282. }
  13283. function renderBwTestHistory(list) {
  13284. const tbody = document.getElementById('bwtest-history-tbody');
  13285. if (!tbody) return;
  13286. if (list.length === 0) {
  13287. 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>`;
  13288. return;
  13289. }
  13290. tbody.innerHTML = '';
  13291. list.forEach(item => {
  13292. const s = item.summary || {};
  13293. const tr = document.createElement('tr');
  13294. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13295. const dirBadge = item.direction === 'both'
  13296. ? `<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>`
  13297. : item.direction === 'tx'
  13298. ? `<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>`
  13299. : `<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>`;
  13300. const protoBadge = item.protocol === 'tcp'
  13301. ? `<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>`
  13302. : `<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>`;
  13303. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13304. tr.innerHTML = `
  13305. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13306. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13307. <td class="py-2.5 px-4">${protoBadge}</td>
  13308. <td class="py-2.5 px-4">${dirBadge}</td>
  13309. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13310. <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>
  13311. <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>
  13312. <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>
  13313. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13314. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13315. `;
  13316. tbody.appendChild(tr);
  13317. });
  13318. }
  13319. // ======================== SETTINGS & ROUTER DNS ========================
  13320. state.settingsSubTab = 'dns';
  13321. state.dnsSettings = null;
  13322. state.dnsStaticRecords = [];
  13323. state.dnsStatus = null;
  13324. function switchSettingsSubTab(sub) {
  13325. state.settingsSubTab = sub;
  13326. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13327. const btnSys = document.getElementById('btn-settings-subtab-system');
  13328. const tabDns = document.getElementById('settings-subtab-dns');
  13329. const tabSys = document.getElementById('settings-subtab-system');
  13330. if (sub === 'dns') {
  13331. if (btnDns) {
  13332. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13333. }
  13334. if (btnSys) {
  13335. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13336. }
  13337. tabDns?.classList.remove('hidden');
  13338. tabSys?.classList.add('hidden');
  13339. loadDNSSettings();
  13340. } else {
  13341. if (btnSys) {
  13342. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13343. }
  13344. if (btnDns) {
  13345. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13346. }
  13347. tabSys?.classList.remove('hidden');
  13348. tabDns?.classList.add('hidden');
  13349. loadSystemSettings();
  13350. }
  13351. }
  13352. async function loadSettingsData(showLoading = false) {
  13353. if (state.settingsSubTab === 'system') {
  13354. await loadSystemSettings();
  13355. } else {
  13356. await loadDNSSettings();
  13357. }
  13358. }
  13359. async function loadDNSSettings() {
  13360. try {
  13361. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13362. fetch(`${API_BASE}/dns/settings`),
  13363. fetch(`${API_BASE}/dns/static`),
  13364. fetch(`${API_BASE}/dns/status`)
  13365. ]);
  13366. if (settingsRes.ok) {
  13367. state.dnsSettings = await settingsRes.json();
  13368. populateDNSSettingsForm(state.dnsSettings);
  13369. }
  13370. if (staticRes.ok) {
  13371. state.dnsStaticRecords = await staticRes.json();
  13372. renderStaticDNSList();
  13373. }
  13374. if (statusRes.ok) {
  13375. state.dnsStatus = await statusRes.json();
  13376. updateDNSStatusView(state.dnsStatus);
  13377. }
  13378. } catch (err) {
  13379. console.error('Failed to load DNS settings:', err);
  13380. }
  13381. }
  13382. function populateDNSSettingsForm(s) {
  13383. if (!s) return;
  13384. const serversInput = document.getElementById('dns-servers-input');
  13385. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13386. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13387. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13388. const domainInput = document.getElementById('dns-domain-input');
  13389. if (domainInput) domainInput.value = s.domain || '';
  13390. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13391. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13392. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13393. if (dynamicEl) {
  13394. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13395. 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(' ');
  13396. } else {
  13397. dynamicEl.innerText = 'None';
  13398. }
  13399. }
  13400. }
  13401. function updateDNSStatusView(st) {
  13402. if (!st) return;
  13403. const preview = document.getElementById('dns-resolv-preview');
  13404. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13405. const pillText = document.getElementById('dns-live-status-text');
  13406. const pill = document.getElementById('dns-live-status-pill');
  13407. if (pill && pillText) {
  13408. if (st.service_running) {
  13409. 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';
  13410. pillText.innerText = 'DNS Service Active';
  13411. } else {
  13412. 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';
  13413. pillText.innerText = 'DNS Service Inactive';
  13414. }
  13415. }
  13416. }
  13417. function appendDNSPreset(preset) {
  13418. const input = document.getElementById('dns-servers-input');
  13419. if (!input) return;
  13420. const current = input.value.trim();
  13421. if (!current) {
  13422. input.value = preset;
  13423. } else {
  13424. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13425. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13426. toAdd.forEach(ip => {
  13427. if (!existing.includes(ip)) existing.push(ip);
  13428. });
  13429. input.value = existing.join(', ');
  13430. }
  13431. }
  13432. async function saveDNSSettings(e) {
  13433. e.preventDefault();
  13434. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13435. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13436. if (servers.length === 0) {
  13437. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13438. return;
  13439. }
  13440. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13441. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13442. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13443. try {
  13444. const res = await fetch(`${API_BASE}/dns/settings`, {
  13445. method: 'POST',
  13446. headers: { 'Content-Type': 'application/json' },
  13447. body: JSON.stringify({
  13448. servers: servers,
  13449. cache_size: cacheSize,
  13450. domain: domain,
  13451. allow_remote_requests: allowRemote
  13452. })
  13453. });
  13454. const data = await res.json();
  13455. if (res.ok) {
  13456. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13457. loadDNSSettings();
  13458. } else {
  13459. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13460. }
  13461. } catch (err) {
  13462. showToast('Error', err.message, 'error');
  13463. }
  13464. }
  13465. async function flushDNSCache() {
  13466. try {
  13467. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13468. if (res.ok) {
  13469. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13470. loadDNSSettings();
  13471. } else {
  13472. const err = await res.json();
  13473. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13474. }
  13475. } catch (err) {
  13476. showToast('Error', err.message, 'error');
  13477. }
  13478. }
  13479. function renderStaticDNSList() {
  13480. const tbody = document.getElementById('dns-static-tbody');
  13481. const empty = document.getElementById('dns-static-empty');
  13482. const badge = document.getElementById('dns-static-count-badge');
  13483. if (!tbody) return;
  13484. tbody.innerHTML = '';
  13485. const records = state.dnsStaticRecords || [];
  13486. if (badge) badge.innerText = `${records.length} Records`;
  13487. if (records.length === 0) {
  13488. empty?.classList.remove('hidden');
  13489. return;
  13490. }
  13491. empty?.classList.add('hidden');
  13492. records.forEach(rec => {
  13493. const tr = document.createElement('tr');
  13494. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  13495. tr.innerHTML = `
  13496. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  13497. <td class="py-2.5 px-4">
  13498. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  13499. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  13500. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  13501. }">
  13502. ${rec.type || 'A'}
  13503. </span>
  13504. </td>
  13505. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  13506. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  13507. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  13508. <td class="py-2.5 px-4">
  13509. <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'}">
  13510. ${rec.disabled ? 'Disabled' : 'Active'}
  13511. </span>
  13512. </td>
  13513. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  13514. <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>
  13515. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  13516. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  13517. </td>
  13518. `;
  13519. tbody.appendChild(tr);
  13520. });
  13521. }
  13522. function openStaticDNSModal(id = null) {
  13523. const modal = document.getElementById('modal-static-dns');
  13524. const title = document.getElementById('modal-static-dns-title');
  13525. const form = document.getElementById('form-static-dns');
  13526. if (!modal || !form) return;
  13527. form.reset();
  13528. document.getElementById('modal-static-dns-id').value = '';
  13529. if (id) {
  13530. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  13531. if (rec) {
  13532. if (title) title.innerText = 'Edit Static DNS Record';
  13533. document.getElementById('modal-static-dns-id').value = rec.id;
  13534. document.getElementById('modal-static-dns-name').value = rec.name;
  13535. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  13536. document.getElementById('modal-static-dns-addr').value = rec.address;
  13537. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  13538. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  13539. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  13540. }
  13541. } else {
  13542. if (title) title.innerText = 'Add Static DNS Record';
  13543. }
  13544. modal.classList.remove('hidden');
  13545. }
  13546. function closeStaticDNSModal() {
  13547. document.getElementById('modal-static-dns')?.classList.add('hidden');
  13548. }
  13549. async function submitSaveStaticDNS(e) {
  13550. e.preventDefault();
  13551. const id = document.getElementById('modal-static-dns-id')?.value || '';
  13552. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  13553. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  13554. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  13555. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  13556. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  13557. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  13558. if (!name || !address) {
  13559. showToast('Validation Error', 'Name and Target Address are required', 'error');
  13560. return;
  13561. }
  13562. try {
  13563. const res = await fetch(`${API_BASE}/dns/static`, {
  13564. method: 'POST',
  13565. headers: { 'Content-Type': 'application/json' },
  13566. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  13567. });
  13568. const data = await res.json();
  13569. if (res.ok) {
  13570. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  13571. closeStaticDNSModal();
  13572. loadDNSSettings();
  13573. } else {
  13574. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  13575. }
  13576. } catch (err) {
  13577. showToast('Error', err.message, 'error');
  13578. }
  13579. }
  13580. async function deleteStaticDNS(id) {
  13581. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  13582. try {
  13583. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13584. if (res.ok) {
  13585. showToast('Deleted', 'Static DNS record deleted', 'success');
  13586. loadDNSSettings();
  13587. }
  13588. } catch (err) {
  13589. showToast('Error', err.message, 'error');
  13590. }
  13591. }
  13592. async function toggleStaticDNS(id, disabled) {
  13593. try {
  13594. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  13595. method: 'POST',
  13596. headers: { 'Content-Type': 'application/json' },
  13597. body: JSON.stringify({ disabled })
  13598. });
  13599. if (res.ok) {
  13600. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  13601. loadDNSSettings();
  13602. }
  13603. } catch (err) {
  13604. showToast('Error', err.message, 'error');
  13605. }
  13606. }
  13607. async function loadSystemSettings() {
  13608. try {
  13609. const res = await fetch(`${API_BASE}/system/settings`);
  13610. if (res.ok) {
  13611. const data = await res.json();
  13612. const hostInput = document.getElementById('system-hostname-input');
  13613. if (hostInput) hostInput.value = data.hostname || '';
  13614. const tzInput = document.getElementById('system-timezone-input');
  13615. if (tzInput && data.timezone) tzInput.value = data.timezone;
  13616. }
  13617. } catch (err) {
  13618. console.error('Failed to load system settings:', err);
  13619. }
  13620. }
  13621. async function saveSystemSettings(e) {
  13622. e.preventDefault();
  13623. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  13624. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  13625. try {
  13626. const res = await fetch(`${API_BASE}/system/settings`, {
  13627. method: 'POST',
  13628. headers: { 'Content-Type': 'application/json' },
  13629. body: JSON.stringify({ hostname, timezone })
  13630. });
  13631. const data = await res.json();
  13632. if (res.ok) {
  13633. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  13634. const sideH = document.getElementById('side-hostname');
  13635. if (sideH) sideH.innerText = data.hostname;
  13636. } else {
  13637. showToast('Error', data.error || 'Failed to save system settings', 'error');
  13638. }
  13639. } catch (err) {
  13640. showToast('Error', err.message, 'error');
  13641. }
  13642. }