app.js 624 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768
  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. };
  133. const header = titles[tabName] || titles.dashboard;
  134. const pTitle = document.getElementById('page-title');
  135. if (pTitle) pTitle.innerText = header.title;
  136. const pSub = document.getElementById('page-subtitle');
  137. if (pSub) pSub.innerText = header.sub;
  138. // Toggle sections dynamically for all section elements
  139. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  140. if (el.id === `section-${tabName}`) {
  141. el.classList.remove('hidden');
  142. } else {
  143. el.classList.add('hidden');
  144. }
  145. });
  146. if (tabName === 'bridge') loadBridge();
  147. if (tabName === 'firewall') loadFirewall();
  148. if (tabName === 'routes') loadRoutes();
  149. if (tabName === 'bgp') {
  150. loadDynamicRouting();
  151. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  152. }
  153. if (tabName === 'ospf') {
  154. loadDynamicRouting();
  155. switchOspfTab(state.activeOspfTab || 'instances');
  156. }
  157. if (tabName === 'routing-filters') loadDynamicRouting();
  158. if (tabName === 'dynamic-routing') loadDynamicRouting();
  159. if (tabName === 'ppp') loadPPP();
  160. if (tabName === 'eoip') loadEoIP();
  161. if (tabName === 'aerotun') loadAeroTUN();
  162. if (tabName === 'persistence') loadDebianConfig();
  163. if (tabName === 'pppoe') loadPPPoE();
  164. if (tabName === 'wireguard') loadWireGuard();
  165. if (tabName === 'ipsec') loadIPSec();
  166. if (tabName === 'l2tp') loadL2TP();
  167. if (tabName === 'pptp') loadPPTP();
  168. if (tabName === 'tools') loadToolsView();
  169. if (tabName === 'dhcp-client') loadDHCPClients();
  170. if (tabName === 'dhcp-server') loadDHCPServer();
  171. if (tabName === 'vrrp') loadVRRP();
  172. if (tabName === 'bwtest') loadBwTestView();
  173. setTimeout(initTableSorting, 50);
  174. }
  175. // Fetch all core system, network and VPN telemetry
  176. async function fetchData(isManual = false) {
  177. const spinner = document.getElementById('refresh-spinner');
  178. if (isManual && spinner) spinner.classList.add('animate-spin');
  179. try {
  180. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  181. fetch(`${API_BASE}/system/status`),
  182. fetch(`${API_BASE}/interfaces`),
  183. fetch(`${API_BASE}/vlans`),
  184. fetch(`${API_BASE}/vpn/status`),
  185. fetch(`${API_BASE}/firewall/summary`),
  186. fetch(`${API_BASE}/routing/dynamic/summary`),
  187. fetch(`${API_BASE}/bridge/summary`),
  188. fetch(`${API_BASE}/dhcp/clients/summary`),
  189. fetch(`${API_BASE}/dhcp/clients`),
  190. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  191. ]);
  192. if (vrrpSumRes && vrrpSumRes.ok) {
  193. state.vrrpSummary = await vrrpSumRes.json();
  194. renderVRRPSummary();
  195. }
  196. if (dhcpSumRes && dhcpSumRes.ok) {
  197. state.dhcpSummary = await dhcpSumRes.json();
  198. const bDhcp = document.getElementById('badge-dhcp-client-count');
  199. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  200. }
  201. if (dhcpClientsRes && dhcpClientsRes.ok) {
  202. state.dhcpClients = await dhcpClientsRes.json();
  203. }
  204. if (brSummaryRes.ok) {
  205. state.bridgeSummary = await brSummaryRes.json();
  206. const bBridge = document.getElementById('badge-bridge-count');
  207. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  208. const sBr = document.getElementById('bridge-stat-bridges');
  209. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  210. const sPorts = document.getElementById('bridge-stat-ports');
  211. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  212. const sHosts = document.getElementById('bridge-stat-hosts');
  213. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  214. }
  215. if (statusRes.ok) state.systemStatus = await statusRes.json();
  216. if (ifacesRes.ok) {
  217. const ifacesData = await ifacesRes.json();
  218. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  219. state.interfaces = rawIfaces.filter(i => {
  220. if (!i.name) return false;
  221. if (i.name.startsWith('ep_')) return false;
  222. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  223. });
  224. try { populateToolsInterfaces(); } catch (e) {}
  225. }
  226. if (vlansRes.ok) {
  227. const vlansData = await vlansRes.json();
  228. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  229. }
  230. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  231. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  232. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  233. updateSystemMetrics();
  234. updateBadges();
  235. if (state.activeTab === 'dashboard') renderDashboard();
  236. if (state.activeTab === 'interfaces') renderInterfacesList();
  237. if (state.activeTab === 'vlans') renderVlansList();
  238. if (state.activeTab === 'firewall') loadFirewall(false);
  239. if (state.activeTab === 'routes') loadRoutes(false);
  240. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  241. if (state.activeTab === 'ppp') loadPPP(false);
  242. if (state.activeTab === 'eoip') loadEoIP(false);
  243. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  244. if (state.activeTab === 'pppoe') loadPPPoE(false);
  245. if (state.activeTab === 'wireguard') loadWireGuard(false);
  246. if (state.activeTab === 'ipsec') loadIPSec(false);
  247. if (state.activeTab === 'l2tp') loadL2TP(false);
  248. if (state.activeTab === 'pptp') loadPPTP(false);
  249. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  250. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  251. if (state.activeTab === 'vrrp') loadVRRP(false);
  252. fetchBwTestServerStatus();
  253. } catch (err) {
  254. console.error('Failed to fetch router state:', err);
  255. } finally {
  256. if (isManual && spinner) {
  257. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  258. }
  259. }
  260. }
  261. // Update Top KPI and Sidebar Telemetry
  262. function updateSystemMetrics() {
  263. const s = state.systemStatus;
  264. const v = state.vpnStatus;
  265. if (!s) return;
  266. // Sidebar Host & Uptime
  267. const sideHost = document.getElementById('side-hostname');
  268. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  269. const sideUp = document.getElementById('side-uptime');
  270. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  271. const sideGw = document.getElementById('side-gateway-ip');
  272. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  273. // Compute CPU Metrics
  274. let cpuPct = 0;
  275. if (s.cpu_pct !== undefined) {
  276. cpuPct = s.cpu_pct;
  277. } else if (s.cpu_load && s.cpu_load.length > 0) {
  278. const cores = s.cpu_cores || 1;
  279. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  280. }
  281. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  282. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  283. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  284. // Sidebar CPU
  285. const sideCpuVal = document.getElementById('side-cpu-val');
  286. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  287. const sideCpuBar = document.getElementById('side-cpu-bar');
  288. if (sideCpuBar) {
  289. sideCpuBar.style.width = cpuWidth;
  290. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  291. }
  292. // Dashboard CPU Card
  293. const dashCpuVal = document.getElementById('dash-cpu-val');
  294. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  295. const dashCpuBar = document.getElementById('dash-cpu-bar');
  296. if (dashCpuBar) {
  297. dashCpuBar.style.width = cpuWidth;
  298. if (cpuPct > 85) {
  299. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  300. } else if (cpuPct > 65) {
  301. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  302. } else {
  303. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  304. }
  305. }
  306. const dashCpuCores = document.getElementById('dash-cpu-cores');
  307. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  308. const dashCpuLoad = document.getElementById('dash-cpu-load');
  309. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  310. const dashCpuStatus = document.getElementById('dash-cpu-status');
  311. if (dashCpuStatus) {
  312. if (cpuPct > 85) {
  313. dashCpuStatus.innerText = 'High';
  314. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  315. } else if (cpuPct > 65) {
  316. dashCpuStatus.innerText = 'Heavy';
  317. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  318. } else {
  319. dashCpuStatus.innerText = 'Normal';
  320. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  321. }
  322. }
  323. // Compute RAM Metrics
  324. const memPct = Math.round(s.mem_usage_pct || 0);
  325. const memPctStr = `${memPct}%`;
  326. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  327. const usedMB = s.mem_used_mb || 0;
  328. const totalMB = s.mem_total_mb || 0;
  329. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  330. function fmtMemMB(mb) {
  331. if (mb >= 1024) {
  332. return `${(mb / 1024).toFixed(1)} GB`;
  333. }
  334. return `${mb} MB`;
  335. }
  336. // Sidebar RAM
  337. const sideRamVal = document.getElementById('side-ram-val');
  338. if (sideRamVal) sideRamVal.innerText = memPctStr;
  339. const sideRamBar = document.getElementById('side-ram-bar');
  340. if (sideRamBar) sideRamBar.style.width = memWidth;
  341. // Dashboard RAM Card
  342. const dashRamVal = document.getElementById('dash-ram-val');
  343. if (dashRamVal) dashRamVal.innerText = memPctStr;
  344. const dashRamBar = document.getElementById('dash-ram-bar');
  345. if (dashRamBar) {
  346. dashRamBar.style.width = memWidth;
  347. if (memPct > 85) {
  348. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  349. } else if (memPct > 70) {
  350. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  351. } else {
  352. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  353. }
  354. }
  355. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  356. if (dashRamUsedTotal) {
  357. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  358. }
  359. const dashRamFree = document.getElementById('dash-ram-free');
  360. if (dashRamFree) {
  361. dashRamFree.innerText = fmtMemMB(freeMB);
  362. }
  363. const dashRamStatus = document.getElementById('dash-ram-status');
  364. if (dashRamStatus) {
  365. if (memPct > 85) {
  366. dashRamStatus.innerText = 'High';
  367. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  368. } else {
  369. dashRamStatus.innerText = 'Active';
  370. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  371. }
  372. }
  373. // Legacy Dashboard Stats (Safe checks)
  374. const elIfacesUp = document.getElementById('stat-ifaces-up');
  375. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  376. const elIfacesTot = document.getElementById('stat-ifaces-total');
  377. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  378. const elIfacesDown = document.getElementById('stat-ifaces-down');
  379. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  380. const elVlans = document.getElementById('stat-vlans-count');
  381. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  382. // VPN Status Indicators
  383. if (v) {
  384. const totalActive = v.total_active_tunnels || 0;
  385. const statVpnActive = document.getElementById('stat-vpn-active');
  386. if (statVpnActive) statVpnActive.innerText = totalActive;
  387. const tunnelsDot = document.getElementById('tunnels-dot');
  388. const tunnelsLabel = document.getElementById('tunnels-label');
  389. if (tunnelsDot && tunnelsLabel) {
  390. if (totalActive > 0) {
  391. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  392. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  393. } else {
  394. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  395. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  396. }
  397. }
  398. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  399. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  400. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  401. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  402. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  403. }
  404. // Total Live Bandwidth Rate
  405. let totalRx = 0;
  406. let totalTx = 0;
  407. (state.interfaces || []).forEach(i => {
  408. if (i.rate) {
  409. totalRx += i.rate.rx_bytes_sec || 0;
  410. totalTx += i.rate.tx_bytes_sec || 0;
  411. }
  412. });
  413. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  414. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  415. }
  416. function setDotBadge(id, active) {
  417. const el = document.getElementById(id);
  418. if (!el) return;
  419. if (active) {
  420. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  421. } else {
  422. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  423. }
  424. }
  425. function updateBadges() {
  426. const bIfaces = document.getElementById('badge-ifaces-count');
  427. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  428. const bVlans = document.getElementById('badge-vlans-count');
  429. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  430. if (state.fwSummary) {
  431. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  432. const badgeFw = document.getElementById('badge-firewall-count');
  433. if (badgeFw) badgeFw.innerText = totalFwRules;
  434. }
  435. if (state.vpnStatus) {
  436. const v = state.vpnStatus;
  437. const bEoIP = document.getElementById('badge-eoip-count');
  438. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  439. const bAero = document.getElementById('badge-aerotun-count');
  440. if (bAero) bAero.innerText = v.total_aerotun || 0;
  441. const bPPPSess = document.getElementById('badge-ppp-sessions');
  442. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  443. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  444. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  445. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  446. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  447. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  448. }
  449. if (state.dynSummary) {
  450. const d = state.dynSummary;
  451. setDotBadge('badge-bgp-dot', d.bgp_running);
  452. setDotBadge('badge-ospf-dot', d.ospf_running);
  453. const bBgp = document.getElementById('badge-bgp-count');
  454. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  455. const bOspf = document.getElementById('badge-ospf-count');
  456. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  457. const bFilters = document.getElementById('badge-filters-count');
  458. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  459. }
  460. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  461. if (bDhcpServer) {
  462. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  463. }
  464. }
  465. // Render Dashboard View
  466. function renderDashboard() {
  467. const matrix = document.getElementById('port-matrix');
  468. matrix.innerHTML = '';
  469. (state.interfaces || []).forEach(iface => {
  470. const isUp = iface.state === 'UP';
  471. const isVlan = iface.is_vlan;
  472. const portCard = document.createElement('div');
  473. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  474. isUp
  475. ? (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')
  476. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  477. }`;
  478. portCard.onclick = () => openIfaceModal(iface.name);
  479. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  480. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  481. portCard.innerHTML = `
  482. <div class="flex items-center justify-between mb-2">
  483. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  484. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  485. </div>
  486. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  487. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  488. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  489. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  490. </div>
  491. `;
  492. matrix.appendChild(portCard);
  493. });
  494. const ifaceTbody = document.getElementById('quick-interfaces-table');
  495. if (ifaceTbody) {
  496. ifaceTbody.innerHTML = '';
  497. (state.interfaces || []).forEach(i => {
  498. const isUp = i.state === 'UP';
  499. const tr = document.createElement('tr');
  500. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  501. tr.onclick = () => openIfaceModal(i.name);
  502. const rxStr = i.rate?.rx_human || '0 B/s';
  503. const txStr = i.rate?.tx_human || '0 B/s';
  504. tr.innerHTML = `
  505. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  506. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  507. <span>${i.name}</span>
  508. </td>
  509. <td class="py-2.5 text-slate-300 font-sans">
  510. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  511. </td>
  512. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  513. <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>
  514. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  515. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  516. </td>
  517. <td class="py-2.5 text-right font-sans font-semibold">
  518. <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>
  519. </td>
  520. `;
  521. ifaceTbody.appendChild(tr);
  522. });
  523. }
  524. const vlanTbody = document.getElementById('quick-vlans-table');
  525. if (vlanTbody) {
  526. vlanTbody.innerHTML = '';
  527. }
  528. }
  529. // Expand / Collapse Handlers
  530. function toggleExpand(parentName) {
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  539. function supportsVLAN(iface) {
  540. if (!iface) return false;
  541. if (iface.is_vlan) return false;
  542. const name = (iface.name || '').toLowerCase();
  543. const type = (iface.type || '').toLowerCase();
  544. const role = (iface.role || '').toLowerCase();
  545. // Exclude loopback
  546. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  547. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  548. if (type === 'wireguard' || name.startsWith('wg')) return false;
  549. // Exclude PPP / PPPoE
  550. if (type === 'ppp' || name.startsWith('ppp')) return false;
  551. // Exclude other Layer 3 tunnels and dummy devices
  552. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  553. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  554. return false;
  555. }
  556. // If name already contains a dot, it's already a sub-interface
  557. if (name.includes('.')) return false;
  558. return true;
  559. }
  560. // Expand / Collapse Handlers
  561. function toggleExpand(parentName) {
  562. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  563. if (childVlans.length === 0) {
  564. // Cannot expand an interface with no VLANs
  565. state.expandedParents.delete(parentName);
  566. return;
  567. }
  568. if (state.expandedParents.has(parentName)) {
  569. state.expandedParents.delete(parentName);
  570. } else {
  571. state.expandedParents.add(parentName);
  572. }
  573. renderInterfacesList();
  574. }
  575. function expandAllIfaces(expand) {
  576. if (expand) {
  577. (state.interfaces || []).forEach(i => {
  578. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  579. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  580. });
  581. } else {
  582. state.expandedParents.clear();
  583. }
  584. renderInterfacesList();
  585. }
  586. // Filter and Render Hierarchical Interfaces List
  587. function filterIfaces(filter) {
  588. state.ifaceFilter = filter || 'all';
  589. renderInterfacesList();
  590. }
  591. function renderInterfacesList() {
  592. const tbody = document.getElementById('interfaces-tree-tbody');
  593. const emptyState = document.getElementById('interfaces-empty-state');
  594. const summary = document.getElementById('ifaces-list-summary');
  595. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  596. tbody.innerHTML = '';
  597. const allIfaces = state.interfaces || [];
  598. const allVlans = state.vlans || [];
  599. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  600. const filteredParents = parentIfaces.filter(parent => {
  601. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  602. if (query) {
  603. const matchName = parent.name.toLowerCase().includes(query);
  604. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  605. const matchRole = (parent.role || '').toLowerCase().includes(query);
  606. const matchType = (parent.type || '').toLowerCase().includes(query);
  607. const matchVlan = childVlans.some(v =>
  608. v.name.toLowerCase().includes(query) ||
  609. String(v.vlan_id).includes(query) ||
  610. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  611. (v.description || '').toLowerCase().includes(query)
  612. );
  613. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  614. }
  615. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  616. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  617. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  618. return true;
  619. });
  620. if (summary) {
  621. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  622. }
  623. if (filteredParents.length === 0) {
  624. emptyState?.classList.remove('hidden');
  625. return;
  626. }
  627. emptyState?.classList.add('hidden');
  628. filteredParents.forEach(parent => {
  629. const isUp = parent.state === 'UP';
  630. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  631. const hasVlans = childVlans.length > 0;
  632. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  633. const canHaveVlan = supportsVLAN(parent);
  634. const parentRow = document.createElement('tr');
  635. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  636. parentRow.innerHTML = `
  637. <td class="py-3 px-3 text-center">
  638. ${hasVlans ? `
  639. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  640. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  641. <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">
  642. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  643. </svg>
  644. </button>
  645. ` : `
  646. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  647. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  648. </div>
  649. `}
  650. </td>
  651. <td class="py-3 px-4">
  652. <div class="flex items-center space-x-2.5">
  653. <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">
  654. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  655. </div>
  656. <div>
  657. <div class="flex items-center gap-2">
  658. <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'}">
  659. <span>${parent.name}</span>
  660. <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>
  661. </span>
  662. ${hasVlans ? `
  663. <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>
  664. ` : `
  665. <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>
  666. `}
  667. </div>
  668. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  669. </div>
  670. </div>
  671. </td>
  672. <td class="py-3 px-4 font-sans">
  673. <div class="flex items-center gap-1.5">
  674. <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>
  675. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  676. </div>
  677. </td>
  678. <td class="py-3 px-4">
  679. ${parent.ipv4 && parent.ipv4.length > 0
  680. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  681. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  682. }
  683. ${(() => {
  684. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  685. if (!c) return '';
  686. 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');
  687. 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>`;
  688. })()}
  689. </td>
  690. <td class="py-3 px-4 text-slate-400 text-[11px]">
  691. <div>${parent.mac || 'N/A'}</div>
  692. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  693. </td>
  694. <td class="py-3 px-4 text-[11px]">
  695. <div class="flex items-center space-x-2">
  696. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  697. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  698. </div>
  699. </td>
  700. <td class="py-3 px-4 font-sans">
  701. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  702. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  703. 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'
  704. }" title="Click to toggle link status">
  705. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  706. <span>${parent.state}</span>
  707. </button>
  708. </td>
  709. <td class="py-3 px-4 text-right space-x-2 font-sans">
  710. ${(() => {
  711. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  712. if (c) {
  713. 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>`;
  714. }
  715. 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>`;
  716. })()}
  717. ${canHaveVlan ? `
  718. <button onclick="openVlanModal('${parent.name}')"
  719. 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">
  720. + Add VLAN
  721. </button>
  722. ` : ''}
  723. <button onclick="openIfaceModal('${parent.name}')"
  724. 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">
  725. Configure
  726. </button>
  727. </td>
  728. `;
  729. tbody.appendChild(parentRow);
  730. if (isExpanded) {
  731. const drawerRow = document.createElement('tr');
  732. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  733. const drawerCell = document.createElement('td');
  734. drawerCell.colSpan = 8;
  735. drawerCell.className = 'p-0';
  736. drawerCell.innerHTML = `
  737. <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">
  738. <div class="flex items-center justify-between mb-3">
  739. <div class="flex items-center space-x-3">
  740. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  741. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  742. </span>
  743. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  744. ${childVlans.length} Attached
  745. </span>
  746. </div>
  747. <button onclick="openVlanModal('${parent.name}')"
  748. 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">
  749. <span>+ Create VLAN on ${parent.name}</span>
  750. </button>
  751. </div>
  752. ${childVlans.length === 0 ? `
  753. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  754. <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>
  755. <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">
  756. <span>+ Create Your First VLAN on ${parent.name}</span>
  757. </button>
  758. </div>
  759. ` : `
  760. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  761. <table class="w-full text-left text-xs font-mono">
  762. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  763. <tr>
  764. <th class="py-2.5 px-4">VLAN ID</th>
  765. <th class="py-2.5 px-4">Interface Device</th>
  766. <th class="py-2.5 px-4">Subnet Gateway</th>
  767. <th class="py-2.5 px-4">Role / Alias</th>
  768. <th class="py-2.5 px-4">MTU</th>
  769. <th class="py-2.5 px-4">Throughput</th>
  770. <th class="py-2.5 px-4">Status</th>
  771. <th class="py-2.5 px-4 text-right">Actions</th>
  772. </tr>
  773. </thead>
  774. <tbody class="divide-y divide-slate-800/70">
  775. ${childVlans.map(v => {
  776. const isVlanUp = v.state === 'UP';
  777. return `
  778. <tr class="hover:bg-slate-800/40 transition">
  779. <td class="py-2.5 px-4">
  780. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  781. VLAN ${v.vlan_id}
  782. </span>
  783. </td>
  784. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  785. <span class="text-cyan-500">└─</span>
  786. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  787. <span>${v.name}</span>
  788. <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>
  789. </span>
  790. </td>
  791. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  792. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  793. ${(() => {
  794. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  795. if (!c) return '';
  796. 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';
  797. 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>`;
  798. })()}
  799. </td>
  800. <td class="py-2.5 px-4 font-sans text-slate-300">
  801. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  802. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  803. </td>
  804. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  805. <td class="py-2.5 px-4 text-[11px]">
  806. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  807. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  808. </td>
  809. <td class="py-2.5 px-4 font-sans">
  810. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  811. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  812. 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'
  813. }">
  814. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  815. <span>${v.state}</span>
  816. </button>
  817. </td>
  818. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  819. ${(() => {
  820. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  821. if (c) {
  822. 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>`;
  823. }
  824. 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>`;
  825. })()}
  826. <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>
  827. <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>
  828. </td>
  829. </tr>
  830. `;
  831. }).join('')}
  832. </tbody>
  833. </table>
  834. </div>
  835. `}
  836. </div>
  837. `;
  838. drawerRow.appendChild(drawerCell);
  839. tbody.appendChild(drawerRow);
  840. }
  841. });
  842. }
  843. // Render VLANs Dedicated View
  844. function renderVlansList() {
  845. const tbody = document.getElementById('vlans-table-body');
  846. if (!tbody) return;
  847. const emptyState = document.getElementById('vlans-empty-state');
  848. const countBadge = document.getElementById('vlans-table-count');
  849. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  850. tbody.innerHTML = '';
  851. const allVlans = state.vlans || [];
  852. if (countBadge) countBadge.innerText = allVlans.length;
  853. const filtered = allVlans.filter(v => {
  854. if (!query) return true;
  855. return v.name.toLowerCase().includes(query) ||
  856. String(v.vlan_id).includes(query) ||
  857. (v.description || '').toLowerCase().includes(query) ||
  858. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  859. });
  860. if (allVlans.length === 0) {
  861. emptyState.classList.remove('hidden');
  862. return;
  863. }
  864. emptyState.classList.add('hidden');
  865. filtered.forEach(v => {
  866. const isUp = v.state === 'UP';
  867. const tr = document.createElement('tr');
  868. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  869. tr.innerHTML = `
  870. <td class="py-3 px-4">
  871. <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">
  872. VLAN ${v.vlan_id}
  873. </span>
  874. </td>
  875. <td class="py-3 px-4 font-bold text-white">
  876. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  877. <span>${v.name}</span>
  878. <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>
  879. </span>
  880. </td>
  881. <td class="py-3 px-4 text-slate-300">
  882. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  883. </td>
  884. <td class="py-3 px-4 text-emerald-400 font-medium">
  885. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  886. </td>
  887. <td class="py-3 px-4 text-slate-300 font-sans">
  888. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  889. </td>
  890. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  891. <td class="py-3 px-4 font-sans">
  892. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  893. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  894. 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'
  895. }">
  896. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  897. <span>${v.state}</span>
  898. </button>
  899. </td>
  900. <td class="py-3 px-4 text-right space-x-2 font-sans">
  901. <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>
  902. <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>
  903. </td>
  904. `;
  905. tbody.appendChild(tr);
  906. });
  907. }
  908. // Toggle interface UP / DOWN
  909. async function toggleInterfaceState(name, newState) {
  910. try {
  911. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  912. method: 'POST',
  913. headers: { 'Content-Type': 'application/json' },
  914. body: JSON.stringify({ state: newState })
  915. });
  916. const data = await res.json();
  917. if (res.ok) {
  918. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  919. fetchData(false);
  920. } else {
  921. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  922. }
  923. } catch (err) {
  924. showToast('Error', err.message, 'error');
  925. }
  926. }
  927. // ---------------- MikroTik Flag & Utilities ----------------
  928. function renderMikroTikFlag(running, disabled) {
  929. if (running) {
  930. 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>`;
  931. }
  932. if (disabled) {
  933. 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>`;
  934. }
  935. 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>`;
  936. }
  937. function copyToClipboard(text, label = 'Text') {
  938. navigator.clipboard.writeText(text).then(() => {
  939. showToast('Copied', `${label} copied to clipboard`, 'success');
  940. }).catch(() => {
  941. prompt('Copy value:', text);
  942. });
  943. }
  944. // ======================== PPP Profiles Shared Helper ========================
  945. async function fetchPPPProfilesList() {
  946. try {
  947. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  948. if (res.ok) {
  949. state.pppProfiles = await res.json();
  950. }
  951. } catch (err) {
  952. console.error('Failed to load PPP profiles:', err);
  953. }
  954. }
  955. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  956. const sel = document.getElementById(selectId);
  957. if (!sel) return;
  958. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  959. { name: 'default', use_encryption: 'no' },
  960. { name: 'default-encryption', use_encryption: 'required' }
  961. ];
  962. sel.innerHTML = '';
  963. profiles.forEach(p => {
  964. const opt = document.createElement('option');
  965. opt.value = p.name;
  966. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  967. opt.innerText = `${p.name}${encBadge}`;
  968. sel.appendChild(opt);
  969. });
  970. if (selectedVal) {
  971. sel.value = selectedVal;
  972. } else {
  973. sel.value = defaultVal;
  974. }
  975. if (!sel.value && sel.options.length > 0) {
  976. sel.selectedIndex = 0;
  977. }
  978. }
  979. // ======================== PPPoE Multi-Instance ========================
  980. async function loadPPPoE(populateInputs = true) {
  981. try {
  982. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  983. await fetchPPPProfilesList();
  984. }
  985. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  986. const list = await res.json();
  987. state.pppoeList = Array.isArray(list) ? list : [];
  988. const badge = document.getElementById('pppoe-count-badge');
  989. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  990. const tbody = document.getElementById('pppoe-table-body');
  991. const empty = document.getElementById('pppoe-empty');
  992. if (!tbody) return;
  993. tbody.innerHTML = '';
  994. if (state.pppoeList.length === 0) {
  995. if (empty) empty.classList.remove('hidden');
  996. } else {
  997. if (empty) empty.classList.add('hidden');
  998. state.pppoeList.forEach(inst => {
  999. const tr = document.createElement('tr');
  1000. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1001. tr.innerHTML = `
  1002. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1003. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1004. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1005. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1006. <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>
  1007. <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>
  1008. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1009. <td class="py-2.5 px-3 text-center">
  1010. <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'}">
  1011. ${inst.default_route ? 'Yes' : 'No'}
  1012. </span>
  1013. </td>
  1014. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1015. ${inst.running ? `
  1016. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1017. ` : `
  1018. <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>
  1019. `}
  1020. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1021. ${inst.disabled ? 'Enable' : 'Disable'}
  1022. </button>
  1023. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1024. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1025. </td>
  1026. `;
  1027. tbody.appendChild(tr);
  1028. });
  1029. }
  1030. } catch (err) {
  1031. console.error('Failed to load PPPoE:', err);
  1032. }
  1033. }
  1034. function openAddPPPoEModal() {
  1035. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1036. document.getElementById('pppoe-modal-edit-orig').value = '';
  1037. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1038. document.getElementById('pppoe-modal-name').readOnly = false;
  1039. document.getElementById('pppoe-modal-user').value = '';
  1040. document.getElementById('pppoe-modal-pass').value = '';
  1041. document.getElementById('pppoe-modal-service').value = '';
  1042. document.getElementById('pppoe-modal-mtu').value = '1492';
  1043. document.getElementById('pppoe-modal-defroute').checked = true;
  1044. document.getElementById('pppoe-modal-reconnect').checked = true;
  1045. document.getElementById('pppoe-modal-disabled').checked = false;
  1046. // Populate profiles
  1047. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1048. // Populate interfaces
  1049. const sel = document.getElementById('pppoe-modal-iface');
  1050. sel.innerHTML = '';
  1051. (state.interfaces || []).forEach(i => {
  1052. if (i.name === 'lo') return;
  1053. const opt = document.createElement('option');
  1054. opt.value = i.name;
  1055. opt.innerText = `${i.name} (${i.role || i.type})`;
  1056. sel.appendChild(opt);
  1057. });
  1058. document.getElementById('pppoe-modal').classList.remove('hidden');
  1059. }
  1060. function openEditPPPoEModal(name) {
  1061. const inst = (state.pppoeList || []).find(i => i.name === name);
  1062. if (!inst) return;
  1063. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1064. document.getElementById('pppoe-modal-edit-orig').value = name;
  1065. document.getElementById('pppoe-modal-name').value = inst.name;
  1066. document.getElementById('pppoe-modal-name').readOnly = true;
  1067. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1068. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1069. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1070. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1071. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1072. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1073. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1074. // Populate profiles
  1075. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1076. const sel = document.getElementById('pppoe-modal-iface');
  1077. sel.innerHTML = '';
  1078. (state.interfaces || []).forEach(i => {
  1079. if (i.name === 'lo') return;
  1080. const opt = document.createElement('option');
  1081. opt.value = i.name;
  1082. opt.innerText = `${i.name} (${i.role || i.type})`;
  1083. if (i.name === inst.interface) opt.selected = true;
  1084. sel.appendChild(opt);
  1085. });
  1086. document.getElementById('pppoe-modal').classList.remove('hidden');
  1087. }
  1088. function closePPPoEModal() {
  1089. document.getElementById('pppoe-modal').classList.add('hidden');
  1090. }
  1091. async function submitSavePPPoE(e) {
  1092. e.preventDefault();
  1093. const name = document.getElementById('pppoe-modal-name').value.trim();
  1094. const iface = document.getElementById('pppoe-modal-iface').value;
  1095. const user = document.getElementById('pppoe-modal-user').value.trim();
  1096. const pass = document.getElementById('pppoe-modal-pass').value;
  1097. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1098. const service = document.getElementById('pppoe-modal-service').value.trim();
  1099. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1100. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1101. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1102. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1103. try {
  1104. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1105. method: 'POST',
  1106. headers: { 'Content-Type': 'application/json' },
  1107. body: JSON.stringify({
  1108. name,
  1109. interface: iface,
  1110. username: user,
  1111. password: pass,
  1112. profile: profile,
  1113. service_name: service,
  1114. mtu,
  1115. default_route: defRoute,
  1116. auto_reconnect: reconnect,
  1117. disabled
  1118. })
  1119. });
  1120. if (res.ok) {
  1121. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1122. closePPPoEModal();
  1123. loadPPPoE(false);
  1124. fetchData(false);
  1125. } else {
  1126. const err = await res.json();
  1127. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1128. }
  1129. } catch (err) {
  1130. showToast('Error', err.message, 'error');
  1131. }
  1132. }
  1133. async function connectPPPoEInstance(name) {
  1134. try {
  1135. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1136. if (res.ok) {
  1137. showToast('Connecting', `Dialing ${name}...`, 'info');
  1138. setTimeout(() => loadPPPoE(false), 2000);
  1139. }
  1140. } catch (err) {
  1141. showToast('Error', err.message, 'error');
  1142. }
  1143. }
  1144. async function disconnectPPPoEInstance(name) {
  1145. try {
  1146. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1147. if (res.ok) {
  1148. showToast('Disconnected', `${name} session terminated`, 'info');
  1149. setTimeout(() => loadPPPoE(false), 1000);
  1150. }
  1151. } catch (err) {
  1152. showToast('Error', err.message, 'error');
  1153. }
  1154. }
  1155. async function togglePPPoEState(name, enable) {
  1156. try {
  1157. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1158. method: 'POST',
  1159. headers: { 'Content-Type': 'application/json' },
  1160. body: JSON.stringify({ enabled: enable })
  1161. });
  1162. if (res.ok) {
  1163. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1164. loadPPPoE(false);
  1165. }
  1166. } catch (err) {
  1167. showToast('Error', err.message, 'error');
  1168. }
  1169. }
  1170. async function deletePPPoEInstance(name) {
  1171. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1172. try {
  1173. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1174. if (res.ok) {
  1175. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1176. loadPPPoE(false);
  1177. fetchData(false);
  1178. }
  1179. } catch (err) {
  1180. showToast('Error', err.message, 'error');
  1181. }
  1182. }
  1183. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1184. state.wgSubTab = 'ifaces';
  1185. function switchWGSubTab(tab) {
  1186. state.wgSubTab = tab;
  1187. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1188. const peersPanel = document.getElementById('wg-subtab-peers');
  1189. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1190. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1191. if (tab === 'ifaces') {
  1192. ifacesPanel?.classList.remove('hidden');
  1193. peersPanel?.classList.add('hidden');
  1194. 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';
  1195. 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';
  1196. } else {
  1197. ifacesPanel?.classList.add('hidden');
  1198. peersPanel?.classList.remove('hidden');
  1199. 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';
  1200. 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';
  1201. renderWGPeers();
  1202. }
  1203. }
  1204. async function loadWireGuard(populateInputs = true) {
  1205. try {
  1206. const [ifacesRes, peersRes] = await Promise.all([
  1207. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1208. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1209. ]);
  1210. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1211. const peers = peersRes.ok ? await peersRes.json() : [];
  1212. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1213. state.wgPeers = Array.isArray(peers) ? peers : [];
  1214. // Badges
  1215. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1216. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1217. const peersCountBadge = document.getElementById('wg-peers-count');
  1218. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1219. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1220. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1221. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1222. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1223. // Render Interfaces
  1224. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1225. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1226. if (ifacesTbody) {
  1227. ifacesTbody.innerHTML = '';
  1228. if (state.wgInterfaces.length === 0) {
  1229. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1230. } else {
  1231. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1232. state.wgInterfaces.forEach(iface => {
  1233. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1234. const tr = document.createElement('tr');
  1235. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1236. tr.innerHTML = `
  1237. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1238. <td class="py-2.5 px-3">
  1239. <div class="flex items-center gap-1.5">
  1240. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1241. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1242. </div>
  1243. </td>
  1244. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1245. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1246. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1247. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1248. ${(iface.public_key || '').substring(0, 10)}... 📋
  1249. </span>
  1250. </td>
  1251. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1252. <td class="py-2.5 px-3 text-center">
  1253. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1254. </td>
  1255. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1256. ${iface.running ? `
  1257. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1258. ` : `
  1259. <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>
  1260. `}
  1261. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1262. ${iface.disabled ? 'Enable' : 'Disable'}
  1263. </button>
  1264. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1265. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1266. </td>
  1267. `;
  1268. ifacesTbody.appendChild(tr);
  1269. });
  1270. }
  1271. }
  1272. // Populate filter dropdown in peers tab
  1273. const filterSel = document.getElementById('wg-peers-filter-iface');
  1274. if (filterSel) {
  1275. const currentVal = filterSel.value;
  1276. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1277. state.wgInterfaces.forEach(i => {
  1278. const opt = document.createElement('option');
  1279. opt.value = i.name;
  1280. opt.innerText = i.name;
  1281. if (i.name === currentVal) opt.selected = true;
  1282. filterSel.appendChild(opt);
  1283. });
  1284. }
  1285. renderWGPeers();
  1286. } catch (err) {
  1287. console.error('Failed to load WireGuard:', err);
  1288. }
  1289. }
  1290. function renderWGPeers() {
  1291. const filterSel = document.getElementById('wg-peers-filter-iface');
  1292. const selectedIface = filterSel ? filterSel.value : '';
  1293. const tbody = document.getElementById('wg-peers-table-body');
  1294. const empty = document.getElementById('wg-peers-empty');
  1295. if (!tbody) return;
  1296. tbody.innerHTML = '';
  1297. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1298. if (filtered.length === 0) {
  1299. if (empty) empty.classList.remove('hidden');
  1300. } else {
  1301. if (empty) empty.classList.add('hidden');
  1302. filtered.forEach(p => {
  1303. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1304. const tr = document.createElement('tr');
  1305. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1306. tr.innerHTML = `
  1307. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1308. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1309. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1310. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1311. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1312. ${(p.public_key || '').substring(0, 10)}... 📋
  1313. </span>
  1314. </td>
  1315. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1316. <td class="py-2.5 px-3 text-slate-400 font-mono">${p.endpoint_address ? (p.endpoint_address + (p.endpoint_port ? ':' + p.endpoint_port : '')) : '--'}</td>
  1317. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1318. <td class="py-2.5 px-3 font-mono text-[11px]">
  1319. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1320. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1321. </td>
  1322. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1323. <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">
  1324. ${p.disabled ? 'Enable' : 'Disable'}
  1325. </button>
  1326. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1327. <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>
  1328. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1329. </td>
  1330. `;
  1331. tbody.appendChild(tr);
  1332. });
  1333. }
  1334. }
  1335. function openAddWGInterfaceModal() {
  1336. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1337. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1338. const nameEl = document.getElementById('wg-iface-modal-name');
  1339. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1340. nameEl.readOnly = false;
  1341. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1342. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1343. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1344. document.getElementById('wg-iface-modal-comment').value = '';
  1345. document.getElementById('wg-iface-modal-pubkey').value = '';
  1346. document.getElementById('wg-iface-modal-privkey').value = '';
  1347. document.getElementById('wg-iface-modal-disabled').checked = false;
  1348. generateWGInterfaceKeys();
  1349. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1350. }
  1351. function openEditWGInterfaceModal(name) {
  1352. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1353. if (!iface) return;
  1354. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1355. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1356. const nameEl = document.getElementById('wg-iface-modal-name');
  1357. nameEl.value = iface.name;
  1358. nameEl.readOnly = false; // ALLOW RENAMING
  1359. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1360. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1361. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1362. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1363. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1364. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1365. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1366. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1367. }
  1368. function closeAddWGInterfaceModal() {
  1369. document.getElementById('wg-iface-modal').classList.add('hidden');
  1370. }
  1371. async function generateWGInterfaceKeys() {
  1372. try {
  1373. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1374. const keys = await res.json();
  1375. if (res.ok) {
  1376. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1377. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1378. }
  1379. } catch (err) {
  1380. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1381. }
  1382. }
  1383. async function onWGInterfacePrivKeyInput() {
  1384. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1385. if (!privKey) return;
  1386. try {
  1387. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1388. method: 'POST',
  1389. headers: { 'Content-Type': 'application/json' },
  1390. body: JSON.stringify({ private_key: privKey })
  1391. });
  1392. if (res.ok) {
  1393. const data = await res.json();
  1394. if (data.public_key) {
  1395. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1396. }
  1397. }
  1398. } catch (err) {
  1399. // Ignore while typing
  1400. }
  1401. }
  1402. function toggleWGPrivKeyVisibility() {
  1403. const el = document.getElementById('wg-iface-modal-privkey');
  1404. const btn = document.getElementById('btn-toggle-wg-privkey');
  1405. if (el.type === 'password') {
  1406. el.type = 'text';
  1407. btn.innerText = '🙈 Hide';
  1408. } else {
  1409. el.type = 'password';
  1410. btn.innerText = '👁️ Show';
  1411. }
  1412. }
  1413. function copyWGInterfacePubKey() {
  1414. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1415. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1416. }
  1417. async function submitSaveWGInterface(e) {
  1418. e.preventDefault();
  1419. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1420. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1421. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1422. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1423. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1424. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1425. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1426. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1427. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1428. try {
  1429. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1430. method: 'POST',
  1431. headers: { 'Content-Type': 'application/json' },
  1432. body: JSON.stringify({
  1433. orig_name: origName,
  1434. name,
  1435. listen_port: port,
  1436. address: addr,
  1437. mtu,
  1438. comment,
  1439. public_key: pub,
  1440. private_key: priv,
  1441. disabled
  1442. })
  1443. });
  1444. const data = await res.json();
  1445. if (res.ok) {
  1446. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1447. closeAddWGInterfaceModal();
  1448. loadWireGuard(false);
  1449. fetchData(false);
  1450. } else {
  1451. showToast('Error', data.error || 'Failed to save interface', 'error');
  1452. }
  1453. } catch (err) {
  1454. showToast('Error', err.message, 'error');
  1455. }
  1456. }
  1457. async function startWGInterface(name) {
  1458. try {
  1459. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1460. if (res.ok) {
  1461. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1462. loadWireGuard(false);
  1463. fetchData(false);
  1464. }
  1465. } catch (err) {
  1466. showToast('Error', err.message, 'error');
  1467. }
  1468. }
  1469. async function stopWGInterface(name) {
  1470. try {
  1471. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1472. if (res.ok) {
  1473. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1474. loadWireGuard(false);
  1475. fetchData(false);
  1476. }
  1477. } catch (err) {
  1478. showToast('Error', err.message, 'error');
  1479. }
  1480. }
  1481. async function toggleWGInterfaceState(name, enable) {
  1482. try {
  1483. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1484. method: 'POST',
  1485. headers: { 'Content-Type': 'application/json' },
  1486. body: JSON.stringify({ enabled: enable })
  1487. });
  1488. if (res.ok) {
  1489. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1490. loadWireGuard(false);
  1491. fetchData(false);
  1492. }
  1493. } catch (err) {
  1494. showToast('Error', err.message, 'error');
  1495. }
  1496. }
  1497. async function deleteWGInterface(name) {
  1498. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1499. try {
  1500. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1501. if (res.ok) {
  1502. showToast('Deleted', `Interface ${name} removed`, 'success');
  1503. loadWireGuard(false);
  1504. fetchData(false);
  1505. }
  1506. } catch (err) {
  1507. showToast('Error', err.message, 'error');
  1508. }
  1509. }
  1510. function populateWGPeerIfaceSelect(selectedIface = '') {
  1511. const sel = document.getElementById('wg-peer-modal-iface');
  1512. if (!sel) return;
  1513. sel.innerHTML = '';
  1514. (state.wgInterfaces || []).forEach(i => {
  1515. const opt = document.createElement('option');
  1516. opt.value = i.name;
  1517. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1518. if (i.name === selectedIface) opt.selected = true;
  1519. sel.appendChild(opt);
  1520. });
  1521. }
  1522. function openAddWGPeerModal() {
  1523. if ((state.wgInterfaces || []).length === 0) {
  1524. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1525. openAddWGInterfaceModal();
  1526. return;
  1527. }
  1528. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1529. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1530. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1531. populateWGPeerIfaceSelect();
  1532. document.getElementById('wg-peer-modal-name').value = '';
  1533. document.getElementById('wg-peer-modal-pubkey').value = '';
  1534. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1535. document.getElementById('wg-peer-modal-endpoint').value = '';
  1536. document.getElementById('wg-peer-modal-port').value = '';
  1537. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1538. document.getElementById('wg-peer-modal-preshared').value = '';
  1539. document.getElementById('wg-peer-modal-disabled').checked = false;
  1540. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1541. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1542. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1543. }
  1544. function openEditWGPeerModal(ifaceName, pubKey) {
  1545. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1546. if (!peer) {
  1547. showToast('Not Found', 'Peer not found', 'warning');
  1548. return;
  1549. }
  1550. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1551. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1552. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1553. populateWGPeerIfaceSelect(peer.interface);
  1554. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1555. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1556. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1557. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1558. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1559. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1560. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1561. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1562. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1563. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1564. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1565. }
  1566. function closeAddWGPeerModal() {
  1567. document.getElementById('wg-peer-modal').classList.add('hidden');
  1568. }
  1569. async function generatePeerKeypairHelper() {
  1570. try {
  1571. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1572. const keys = await res.json();
  1573. if (res.ok) {
  1574. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1575. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1576. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1577. checkWGPeerKeyValidity();
  1578. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1579. }
  1580. } catch (err) {
  1581. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1582. }
  1583. }
  1584. function copyGeneratedPeerPrivKey() {
  1585. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1586. if (priv) copyToClipboard(priv, 'Client Private Key');
  1587. }
  1588. async function generatePeerPSK() {
  1589. try {
  1590. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1591. const keys = await res.json();
  1592. if (res.ok && keys.private_key) {
  1593. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1594. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1595. }
  1596. } catch (err) {
  1597. showToast('Error', err.message, 'error');
  1598. }
  1599. }
  1600. function checkWGPeerKeyValidity() {
  1601. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1602. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1603. const warningEl = document.getElementById('wg-peer-key-warning');
  1604. if (!warningEl) return;
  1605. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1606. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1607. warningEl.classList.remove('hidden');
  1608. } else {
  1609. warningEl.classList.add('hidden');
  1610. }
  1611. }
  1612. async function submitSaveWGPeer(e) {
  1613. e.preventDefault();
  1614. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1615. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1616. const iface = document.getElementById('wg-peer-modal-iface').value;
  1617. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1618. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1619. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1620. .split(',')
  1621. .map(s => s.trim())
  1622. .filter(s => s.length > 0);
  1623. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1624. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1625. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1626. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1627. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1628. // Validation
  1629. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1630. if (targetIface && targetIface.public_key === pub) {
  1631. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1632. return;
  1633. }
  1634. try {
  1635. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1636. method: 'POST',
  1637. headers: { 'Content-Type': 'application/json' },
  1638. body: JSON.stringify({
  1639. orig_interface: origIface,
  1640. orig_public_key: origPubKey,
  1641. interface: iface,
  1642. name,
  1643. public_key: pub,
  1644. allowed_ips: allowed,
  1645. endpoint_address: epHost,
  1646. endpoint_port: epPort,
  1647. persistent_keepalive: keepalive,
  1648. preshared_key: psk,
  1649. disabled
  1650. })
  1651. });
  1652. const data = await res.json();
  1653. if (res.ok) {
  1654. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1655. closeAddWGPeerModal();
  1656. loadWireGuard(false);
  1657. } else {
  1658. showToast('Error', data.error || 'Failed to save peer', 'error');
  1659. }
  1660. } catch (err) {
  1661. showToast('Error', err.message, 'error');
  1662. }
  1663. }
  1664. async function toggleWGPeerState(iface, pubkey, enable) {
  1665. try {
  1666. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1667. method: 'POST',
  1668. headers: { 'Content-Type': 'application/json' },
  1669. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1670. });
  1671. const data = await res.json();
  1672. if (res.ok) {
  1673. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1674. loadWireGuard(false);
  1675. } else {
  1676. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1677. }
  1678. } catch (err) {
  1679. showToast('Error', err.message, 'error');
  1680. }
  1681. }
  1682. async function deleteWGPeer(iface, pubkey) {
  1683. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1684. try {
  1685. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1686. method: 'POST',
  1687. headers: { 'Content-Type': 'application/json' },
  1688. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1689. });
  1690. const data = await res.json();
  1691. if (res.ok) {
  1692. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1693. loadWireGuard(false);
  1694. } else {
  1695. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1696. }
  1697. } catch (err) {
  1698. showToast('Error', err.message, 'error');
  1699. }
  1700. }
  1701. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1702. function switchIpsecModalTab(tab) {
  1703. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1704. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1705. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1706. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1707. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1708. if (tab === 'p1') {
  1709. if (p1Tab) {
  1710. 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';
  1711. }
  1712. if (p2Tab) {
  1713. 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';
  1714. }
  1715. if (p1Content) p1Content.classList.remove('hidden');
  1716. if (p2Content) p2Content.classList.add('hidden');
  1717. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1718. } else {
  1719. if (p1Tab) {
  1720. 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';
  1721. }
  1722. if (p2Tab) {
  1723. 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';
  1724. }
  1725. if (p1Content) p1Content.classList.add('hidden');
  1726. if (p2Content) p2Content.classList.remove('hidden');
  1727. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1728. }
  1729. }
  1730. function toggleIpsecPhaseStep() {
  1731. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1732. if (p1Content && !p1Content.classList.contains('hidden')) {
  1733. switchIpsecModalTab('p2');
  1734. } else {
  1735. switchIpsecModalTab('p1');
  1736. }
  1737. }
  1738. function toggleIpsecPskVisibility() {
  1739. const pskInput = document.getElementById('ipsec-modal-psk');
  1740. if (!pskInput) return;
  1741. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1742. }
  1743. function addIpsecLocalSubnet(val = '') {
  1744. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1745. if (!container) return;
  1746. const row = document.createElement('div');
  1747. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1748. row.innerHTML = `
  1749. <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">
  1750. <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>
  1751. `;
  1752. container.appendChild(row);
  1753. }
  1754. function addIpsecRemoteSubnet(val = '') {
  1755. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1756. if (!container) return;
  1757. const row = document.createElement('div');
  1758. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1759. row.innerHTML = `
  1760. <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">
  1761. <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>
  1762. `;
  1763. container.appendChild(row);
  1764. }
  1765. function updateIpsecEspProposalFromPFS(val) {
  1766. const prop = document.getElementById('ipsec-modal-espprop');
  1767. if (!prop) return;
  1768. if (val === 'none') {
  1769. prop.value = 'aes256-sha256,aes128-sha256,default';
  1770. } else {
  1771. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1772. }
  1773. }
  1774. function updateIpsecIkeProposalFromDH(dh) {
  1775. const el = document.getElementById('ipsec-modal-ikeprop');
  1776. if (el) {
  1777. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1778. }
  1779. }
  1780. function safeSetVal(id, val) {
  1781. const el = document.getElementById(id);
  1782. if (el) el.value = val;
  1783. }
  1784. function safeSetChecked(id, val) {
  1785. const el = document.getElementById(id);
  1786. if (el) el.checked = !!val;
  1787. }
  1788. function safeGetVal(id, def = '') {
  1789. const el = document.getElementById(id);
  1790. return el ? el.value : def;
  1791. }
  1792. async function loadIPSec(populateInputs = true) {
  1793. try {
  1794. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1795. const list = await res.json();
  1796. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1797. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1798. const badge = document.getElementById('ipsec-sas-badge');
  1799. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1800. const tbody = document.getElementById('ipsec-table-body');
  1801. const empty = document.getElementById('ipsec-empty');
  1802. if (!tbody) return;
  1803. tbody.innerHTML = '';
  1804. if (state.ipsecTunnels.length === 0) {
  1805. if (empty) empty.classList.remove('hidden');
  1806. } else {
  1807. if (empty) empty.classList.add('hidden');
  1808. state.ipsecTunnels.forEach(c => {
  1809. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1810. const tr = document.createElement('tr');
  1811. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1812. // Local subnets tags
  1813. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1814. 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('');
  1815. // Remote subnets tags
  1816. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1817. 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('');
  1818. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1819. const p2Name = c.phase2_name || `${c.name}_p2`;
  1820. tr.innerHTML = `
  1821. <td class="py-2.5 px-3 text-center">
  1822. ${isEstablished ? `
  1823. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1824. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1825. <span>UP</span>
  1826. </span>
  1827. ` : (c.disabled ? `
  1828. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1829. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1830. <span>DOWN</span>
  1831. </span>
  1832. ` : `
  1833. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1834. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1835. <span>IDLE</span>
  1836. </span>
  1837. `)}
  1838. </td>
  1839. <td class="py-2.5 px-4 font-bold text-white">
  1840. <div class="flex items-center gap-2">
  1841. <span class="text-amber-400">🛡</span>
  1842. <div>
  1843. <div>${escapeHtml(c.name)}</div>
  1844. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1845. </div>
  1846. </div>
  1847. </td>
  1848. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1849. <td class="py-2.5 px-4 font-sans">
  1850. <div class="flex items-center gap-1.5">
  1851. <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>
  1852. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1853. </div>
  1854. </td>
  1855. <td class="py-2.5 px-4">
  1856. <div class="space-y-1">
  1857. <div class="flex items-center flex-wrap gap-1">
  1858. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1859. ${localBadges}
  1860. </div>
  1861. <div class="flex items-center flex-wrap gap-1">
  1862. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1863. ${remoteBadges}
  1864. </div>
  1865. </div>
  1866. </td>
  1867. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1868. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1869. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1870. </div>
  1871. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1872. </td>
  1873. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1874. ${isEstablished ? `
  1875. <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>
  1876. ` : `
  1877. <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>
  1878. `}
  1879. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1880. ${c.disabled ? 'Enable' : 'Disable'}
  1881. </button>
  1882. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1883. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1884. </td>
  1885. `;
  1886. tbody.appendChild(tr);
  1887. });
  1888. }
  1889. } catch (err) {
  1890. console.error('Failed to load IPSec:', err);
  1891. }
  1892. }
  1893. function openAddIPSecModal() {
  1894. const modal = document.getElementById('ipsec-modal');
  1895. if (!modal) return;
  1896. const title = document.getElementById('ipsec-modal-title');
  1897. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1898. // Phase 1 Fields
  1899. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1900. const nameEl = document.getElementById('ipsec-modal-name');
  1901. if (nameEl) nameEl.readOnly = false;
  1902. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1903. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1904. safeSetVal('ipsec-modal-remotegw', '');
  1905. safeSetVal('ipsec-modal-localaddrs', '');
  1906. safeSetVal('ipsec-modal-comments', '');
  1907. safeSetVal('ipsec-modal-psk', '');
  1908. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1909. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1910. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1911. safeSetVal('ipsec-modal-localid', '');
  1912. safeSetVal('ipsec-modal-remoteid', '');
  1913. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1914. // Phase 2 Fields
  1915. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1916. safeSetVal('ipsec-modal-espkeylife', '28800');
  1917. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1918. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1919. safeSetChecked('ipsec-modal-autostart', true);
  1920. safeSetChecked('ipsec-modal-disabled', false);
  1921. // Clear & Populate default dynamic subnets
  1922. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1923. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1924. if (localContainer) {
  1925. localContainer.innerHTML = '';
  1926. addIpsecLocalSubnet('192.168.10.0/24');
  1927. }
  1928. if (remoteContainer) {
  1929. remoteContainer.innerHTML = '';
  1930. addIpsecRemoteSubnet('192.168.20.0/24');
  1931. }
  1932. switchIpsecModalTab('p1');
  1933. modal.classList.remove('hidden');
  1934. }
  1935. function openEditIPSecModal(name) {
  1936. const modal = document.getElementById('ipsec-modal');
  1937. if (!modal) return;
  1938. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1939. if (!conn) return;
  1940. const title = document.getElementById('ipsec-modal-title');
  1941. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1942. // Phase 1 Fields
  1943. safeSetVal('ipsec-modal-name', conn.name);
  1944. const nameEl = document.getElementById('ipsec-modal-name');
  1945. if (nameEl) nameEl.readOnly = true;
  1946. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1947. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1948. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1949. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1950. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1951. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1952. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1953. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1954. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1955. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1956. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1957. // Phase 2 Fields
  1958. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1959. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1960. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1961. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1962. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1963. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1964. // Populate dynamic subnets
  1965. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1966. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1967. if (localContainer) {
  1968. localContainer.innerHTML = '';
  1969. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1970. locals.forEach(s => addIpsecLocalSubnet(s));
  1971. }
  1972. if (remoteContainer) {
  1973. remoteContainer.innerHTML = '';
  1974. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1975. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1976. }
  1977. switchIpsecModalTab('p1');
  1978. modal.classList.remove('hidden');
  1979. }
  1980. function closeAddIPSecModal() {
  1981. const modal = document.getElementById('ipsec-modal');
  1982. if (modal) modal.classList.add('hidden');
  1983. }
  1984. async function submitSaveIPSec(e) {
  1985. if (e) e.preventDefault();
  1986. const name = safeGetVal('ipsec-modal-name').trim();
  1987. if (!name) {
  1988. showToast('Error', 'Tunnel name is required', 'error');
  1989. return;
  1990. }
  1991. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1992. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1993. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1994. const comments = safeGetVal('ipsec-modal-comments').trim();
  1995. const psk = safeGetVal('ipsec-modal-psk');
  1996. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1997. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1998. const localId = safeGetVal('ipsec-modal-localid').trim();
  1999. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2000. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2001. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2002. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2003. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2004. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2005. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2006. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2007. // Scrape dynamic local and remote subnets
  2008. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2009. const localSubnets = [];
  2010. localInputs.forEach(inp => {
  2011. const v = inp.value.trim();
  2012. if (v) localSubnets.push(v);
  2013. });
  2014. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2015. const remoteSubnets = [];
  2016. remoteInputs.forEach(inp => {
  2017. const v = inp.value.trim();
  2018. if (v) remoteSubnets.push(v);
  2019. });
  2020. try {
  2021. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2022. method: 'POST',
  2023. headers: { 'Content-Type': 'application/json' },
  2024. body: JSON.stringify({
  2025. name,
  2026. comment: comments,
  2027. ike_version: ikeVersion,
  2028. local_addrs: localAddrs,
  2029. remote_addrs: remotegw,
  2030. preshared_key: psk,
  2031. ike_proposals: ikeProposals,
  2032. ike_keylife: ikeKeylife,
  2033. local_id: localId,
  2034. remote_id: remoteId,
  2035. dpd: dpd,
  2036. phase2_name: phase2Name,
  2037. esp_proposals: espProposals,
  2038. esp_keylife: espKeylife,
  2039. pfs_group: pfsGroup,
  2040. pfs: pfsGroup !== 'none',
  2041. local_subnets: localSubnets,
  2042. remote_subnets: remoteSubnets,
  2043. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2044. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2045. auto_start: autostart,
  2046. disabled
  2047. })
  2048. });
  2049. if (res.ok) {
  2050. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2051. closeAddIPSecModal();
  2052. loadIPSec(false);
  2053. } else {
  2054. const err = await res.json();
  2055. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2056. }
  2057. } catch (err) {
  2058. showToast('Error', err.message, 'error');
  2059. }
  2060. }
  2061. async function startIPSecTunnel(name) {
  2062. try {
  2063. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2064. if (res.ok) {
  2065. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2066. setTimeout(() => loadIPSec(false), 2000);
  2067. }
  2068. } catch (err) {
  2069. showToast('Error', err.message, 'error');
  2070. }
  2071. }
  2072. async function stopIPSecTunnel(name) {
  2073. try {
  2074. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2075. if (res.ok) {
  2076. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2077. loadIPSec(false);
  2078. }
  2079. } catch (err) {
  2080. showToast('Error', err.message, 'error');
  2081. }
  2082. }
  2083. async function toggleIPSecState(name, enable) {
  2084. try {
  2085. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2086. method: 'POST',
  2087. headers: { 'Content-Type': 'application/json' },
  2088. body: JSON.stringify({ enabled: enable })
  2089. });
  2090. if (res.ok) {
  2091. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2092. loadIPSec(false);
  2093. }
  2094. } catch (err) {
  2095. showToast('Error', err.message, 'error');
  2096. }
  2097. }
  2098. async function deleteIPSecConn(name) {
  2099. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2100. try {
  2101. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2102. if (res.ok) {
  2103. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2104. loadIPSec(false);
  2105. fetchData(false);
  2106. }
  2107. } catch (err) {
  2108. showToast('Error', err.message, 'error');
  2109. }
  2110. }
  2111. // ======================== L2TP Multi-Instance ========================
  2112. async function loadL2TP(populateInputs = true) {
  2113. try {
  2114. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2115. await fetchPPPProfilesList();
  2116. }
  2117. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2118. const list = await res.json();
  2119. state.l2tpList = Array.isArray(list) ? list : [];
  2120. const badge = document.getElementById('l2tp-count-badge');
  2121. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2122. const tbody = document.getElementById('l2tp-table-body');
  2123. const empty = document.getElementById('l2tp-empty');
  2124. if (!tbody) return;
  2125. tbody.innerHTML = '';
  2126. if (state.l2tpList.length === 0) {
  2127. if (empty) empty.classList.remove('hidden');
  2128. } else {
  2129. if (empty) empty.classList.add('hidden');
  2130. state.l2tpList.forEach(inst => {
  2131. const tr = document.createElement('tr');
  2132. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2133. tr.innerHTML = `
  2134. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2135. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2136. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2137. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2138. <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>
  2139. <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>
  2140. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2141. <td class="py-2.5 px-3 text-center">
  2142. <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'}">
  2143. ${inst.default_route ? 'Yes' : 'No'}
  2144. </span>
  2145. </td>
  2146. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2147. ${inst.running ? `
  2148. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2149. ` : `
  2150. <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>
  2151. `}
  2152. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2153. ${inst.disabled ? 'Enable' : 'Disable'}
  2154. </button>
  2155. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2156. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2157. </td>
  2158. `;
  2159. tbody.appendChild(tr);
  2160. });
  2161. }
  2162. } catch (err) {
  2163. console.error('Failed to load L2TP:', err);
  2164. }
  2165. }
  2166. async function openAddL2TPModal() {
  2167. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2168. await fetchPPPProfilesList();
  2169. }
  2170. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2171. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2172. document.getElementById('l2tp-modal-name').readOnly = false;
  2173. document.getElementById('l2tp-modal-server').value = '';
  2174. document.getElementById('l2tp-modal-user').value = '';
  2175. document.getElementById('l2tp-modal-pass').value = '';
  2176. document.getElementById('l2tp-modal-ipsec').value = '';
  2177. document.getElementById('l2tp-modal-defroute').checked = true;
  2178. document.getElementById('l2tp-modal-disabled').checked = false;
  2179. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2180. document.getElementById('l2tp-modal').classList.remove('hidden');
  2181. }
  2182. async function openEditL2TPModal(name) {
  2183. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2184. await fetchPPPProfilesList();
  2185. }
  2186. const inst = (state.l2tpList || []).find(i => i.name === name);
  2187. if (!inst) return;
  2188. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2189. document.getElementById('l2tp-modal-name').value = inst.name;
  2190. document.getElementById('l2tp-modal-name').readOnly = true;
  2191. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2192. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2193. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2194. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2195. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2196. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2197. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2198. document.getElementById('l2tp-modal').classList.remove('hidden');
  2199. }
  2200. function closeL2TPModal() {
  2201. document.getElementById('l2tp-modal').classList.add('hidden');
  2202. }
  2203. async function submitSaveL2TP(e) {
  2204. e.preventDefault();
  2205. const name = document.getElementById('l2tp-modal-name').value.trim();
  2206. const server = document.getElementById('l2tp-modal-server').value.trim();
  2207. const user = document.getElementById('l2tp-modal-user').value.trim();
  2208. const pass = document.getElementById('l2tp-modal-pass').value;
  2209. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2210. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2211. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2212. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2213. try {
  2214. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2215. method: 'POST',
  2216. headers: { 'Content-Type': 'application/json' },
  2217. body: JSON.stringify({
  2218. name,
  2219. connect_to: server,
  2220. username: user,
  2221. password: pass,
  2222. profile: profile,
  2223. ipsec_secret: ipsec,
  2224. default_route: defRoute,
  2225. disabled
  2226. })
  2227. });
  2228. if (res.ok) {
  2229. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2230. closeL2TPModal();
  2231. loadL2TP(false);
  2232. fetchData(false);
  2233. }
  2234. } catch (err) {
  2235. showToast('Error', err.message, 'error');
  2236. }
  2237. }
  2238. async function connectL2TPInstance(name) {
  2239. try {
  2240. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2241. if (res.ok) {
  2242. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2243. setTimeout(() => loadL2TP(false), 2000);
  2244. }
  2245. } catch (err) {
  2246. showToast('Error', err.message, 'error');
  2247. }
  2248. }
  2249. async function disconnectL2TPInstance(name) {
  2250. try {
  2251. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2252. if (res.ok) {
  2253. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2254. loadL2TP(false);
  2255. }
  2256. } catch (err) {
  2257. showToast('Error', err.message, 'error');
  2258. }
  2259. }
  2260. async function toggleL2TPState(name, enable) {
  2261. try {
  2262. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2263. method: 'POST',
  2264. headers: { 'Content-Type': 'application/json' },
  2265. body: JSON.stringify({ enabled: enable })
  2266. });
  2267. if (res.ok) {
  2268. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2269. loadL2TP(false);
  2270. }
  2271. } catch (err) {
  2272. showToast('Error', err.message, 'error');
  2273. }
  2274. }
  2275. async function deleteL2TPInstance(name) {
  2276. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2279. if (res.ok) {
  2280. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2281. loadL2TP(false);
  2282. fetchData(false);
  2283. }
  2284. } catch (err) {
  2285. showToast('Error', err.message, 'error');
  2286. }
  2287. }
  2288. // ======================== PPTP Multi-Instance ========================
  2289. async function loadPPTP(populateInputs = true) {
  2290. try {
  2291. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2292. await fetchPPPProfilesList();
  2293. }
  2294. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2295. const list = await res.json();
  2296. state.pptpList = Array.isArray(list) ? list : [];
  2297. const badge = document.getElementById('pptp-count-badge');
  2298. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2299. const tbody = document.getElementById('pptp-table-body');
  2300. const empty = document.getElementById('pptp-empty');
  2301. if (!tbody) return;
  2302. tbody.innerHTML = '';
  2303. if (state.pptpList.length === 0) {
  2304. if (empty) empty.classList.remove('hidden');
  2305. } else {
  2306. if (empty) empty.classList.add('hidden');
  2307. state.pptpList.forEach(inst => {
  2308. const tr = document.createElement('tr');
  2309. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2310. tr.innerHTML = `
  2311. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2312. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2313. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2314. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2315. <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>
  2316. <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>
  2317. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2318. <td class="py-2.5 px-3 text-center">
  2319. <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'}">
  2320. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2321. </span>
  2322. </td>
  2323. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2324. ${inst.running ? `
  2325. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2326. ` : `
  2327. <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>
  2328. `}
  2329. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2330. ${inst.disabled ? 'Enable' : 'Disable'}
  2331. </button>
  2332. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2333. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2334. </td>
  2335. `;
  2336. tbody.appendChild(tr);
  2337. });
  2338. }
  2339. } catch (err) {
  2340. console.error('Failed to load PPTP:', err);
  2341. }
  2342. }
  2343. async function openAddPPTPModal() {
  2344. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2345. await fetchPPPProfilesList();
  2346. }
  2347. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2348. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2349. document.getElementById('pptp-modal-name').readOnly = false;
  2350. document.getElementById('pptp-modal-server').value = '';
  2351. document.getElementById('pptp-modal-user').value = '';
  2352. document.getElementById('pptp-modal-pass').value = '';
  2353. document.getElementById('pptp-modal-mppe').checked = true;
  2354. document.getElementById('pptp-modal-defroute').checked = true;
  2355. document.getElementById('pptp-modal-disabled').checked = false;
  2356. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2357. document.getElementById('pptp-modal').classList.remove('hidden');
  2358. }
  2359. async function openEditPPTPModal(name) {
  2360. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2361. await fetchPPPProfilesList();
  2362. }
  2363. const inst = (state.pptpList || []).find(i => i.name === name);
  2364. if (!inst) return;
  2365. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2366. document.getElementById('pptp-modal-name').value = inst.name;
  2367. document.getElementById('pptp-modal-name').readOnly = true;
  2368. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2369. document.getElementById('pptp-modal-user').value = inst.username || '';
  2370. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2371. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2372. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2373. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2374. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2375. document.getElementById('pptp-modal').classList.remove('hidden');
  2376. }
  2377. function closePPTPModal() {
  2378. document.getElementById('pptp-modal').classList.add('hidden');
  2379. }
  2380. async function submitSavePPTP(e) {
  2381. e.preventDefault();
  2382. const name = document.getElementById('pptp-modal-name').value.trim();
  2383. const server = document.getElementById('pptp-modal-server').value.trim();
  2384. const user = document.getElementById('pptp-modal-user').value.trim();
  2385. const pass = document.getElementById('pptp-modal-pass').value;
  2386. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2387. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2388. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2389. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2390. try {
  2391. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2392. method: 'POST',
  2393. headers: { 'Content-Type': 'application/json' },
  2394. body: JSON.stringify({
  2395. name,
  2396. connect_to: server,
  2397. username: user,
  2398. password: pass,
  2399. profile: profile,
  2400. require_mppe: mppe,
  2401. default_route: defRoute,
  2402. auto_reconnect: true,
  2403. disabled
  2404. })
  2405. });
  2406. if (res.ok) {
  2407. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2408. closePPTPModal();
  2409. loadPPTP(false);
  2410. fetchData(false);
  2411. }
  2412. } catch (err) {
  2413. showToast('Error', err.message, 'error');
  2414. }
  2415. }
  2416. async function connectPPTPInstance(name) {
  2417. try {
  2418. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2419. if (res.ok) {
  2420. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2421. setTimeout(() => loadPPTP(false), 2000);
  2422. }
  2423. } catch (err) {
  2424. showToast('Error', err.message, 'error');
  2425. }
  2426. }
  2427. async function disconnectPPTPInstance(name) {
  2428. try {
  2429. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2430. if (res.ok) {
  2431. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2432. loadPPTP(false);
  2433. }
  2434. } catch (err) {
  2435. showToast('Error', err.message, 'error');
  2436. }
  2437. }
  2438. async function togglePPTPState(name, enable) {
  2439. try {
  2440. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2441. method: 'POST',
  2442. headers: { 'Content-Type': 'application/json' },
  2443. body: JSON.stringify({ enabled: enable })
  2444. });
  2445. if (res.ok) {
  2446. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2447. loadPPTP(false);
  2448. }
  2449. } catch (err) {
  2450. showToast('Error', err.message, 'error');
  2451. }
  2452. }
  2453. async function deletePPTPInstance(name) {
  2454. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2455. try {
  2456. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2457. if (res.ok) {
  2458. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2459. loadPPTP(false);
  2460. fetchData(false);
  2461. }
  2462. } catch (err) {
  2463. showToast('Error', err.message, 'error');
  2464. }
  2465. }
  2466. // ---------------- Modal & Helper Functions ----------------
  2467. function openVlanModal(defaultParent = '') {
  2468. const select = document.getElementById('vlan-parent');
  2469. select.innerHTML = '';
  2470. const allIfaces = state.interfaces || [];
  2471. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2472. if (eligible.length === 0) {
  2473. const opt = document.createElement('option');
  2474. opt.value = '';
  2475. opt.innerText = 'No VLAN-capable interfaces available';
  2476. select.appendChild(opt);
  2477. } else {
  2478. eligible.forEach(i => {
  2479. const opt = document.createElement('option');
  2480. opt.value = i.name;
  2481. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2482. if (i.name === defaultParent) opt.selected = true;
  2483. select.appendChild(opt);
  2484. });
  2485. }
  2486. document.getElementById('vlan-id').value = '';
  2487. document.getElementById('vlan-name').value = '';
  2488. document.getElementById('vlan-ip').value = '';
  2489. document.getElementById('vlan-desc').value = '';
  2490. autoSuggestVlanName();
  2491. document.getElementById('vlan-modal').classList.remove('hidden');
  2492. }
  2493. function closeVlanModal() {
  2494. document.getElementById('vlan-modal').classList.add('hidden');
  2495. }
  2496. function autoSuggestVlanName() {
  2497. const parent = document.getElementById('vlan-parent').value;
  2498. if (!parent) return;
  2499. const id = document.getElementById('vlan-id').value;
  2500. const nameInput = document.getElementById('vlan-name');
  2501. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2502. }
  2503. function setSubnetPreset(cidr) {
  2504. const ipInput = document.getElementById('vlan-ip');
  2505. const id = document.getElementById('vlan-id').value || '10';
  2506. ipInput.value = `192.168.${id}.1${cidr}`;
  2507. }
  2508. async function submitCreateVlan(e) {
  2509. e.preventDefault();
  2510. const btn = document.getElementById('vlan-submit-btn');
  2511. btn.disabled = true;
  2512. btn.innerText = 'Creating...';
  2513. const parent = document.getElementById('vlan-parent').value;
  2514. if (!parent) {
  2515. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2516. btn.disabled = false;
  2517. btn.innerText = 'Create VLAN';
  2518. return;
  2519. }
  2520. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2521. const name = document.getElementById('vlan-name').value.trim();
  2522. const ip = document.getElementById('vlan-ip').value.trim();
  2523. const role = document.getElementById('vlan-role').value;
  2524. const desc = document.getElementById('vlan-desc').value.trim();
  2525. try {
  2526. const res = await fetch(`${API_BASE}/vlans`, {
  2527. method: 'POST',
  2528. headers: { 'Content-Type': 'application/json' },
  2529. body: JSON.stringify({
  2530. parent_name: parent,
  2531. vlan_id: id,
  2532. name: name,
  2533. ip_address: ip,
  2534. role: role,
  2535. description: desc,
  2536. mtu: 1500,
  2537. auto_up: true
  2538. })
  2539. });
  2540. const data = await res.json();
  2541. if (res.ok) {
  2542. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2543. state.expandedParents.add(parent);
  2544. closeVlanModal();
  2545. await fetchData(true);
  2546. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2547. } else {
  2548. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2549. }
  2550. } catch (err) {
  2551. showToast('Error', err.message, 'error');
  2552. } finally {
  2553. btn.disabled = false;
  2554. btn.innerText = 'Create VLAN';
  2555. }
  2556. }
  2557. async function confirmDeleteVlan(name) {
  2558. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2559. try {
  2560. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2561. if (res.ok) {
  2562. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2563. closeIfaceModal();
  2564. fetchData(true);
  2565. }
  2566. } catch (err) {
  2567. showToast('Error', err.message, 'error');
  2568. }
  2569. }
  2570. function openIfaceModal(name) {
  2571. const iface = (state.interfaces || []).find(i => i.name === name);
  2572. if (!iface) return;
  2573. state.currentModalIface = iface.name;
  2574. document.getElementById('modal-iface-name').innerText = iface.name;
  2575. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2576. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2577. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2578. document.getElementById('modal-iface-desc').value = iface.description || '';
  2579. const nameInput = document.getElementById('modal-iface-new-name');
  2580. const renameBtn = document.getElementById('modal-btn-rename');
  2581. const renameHelp = document.getElementById('modal-iface-rename-help');
  2582. if (nameInput) {
  2583. nameInput.value = iface.name;
  2584. if (iface.name === 'lo' || iface.type === 'loopback') {
  2585. nameInput.disabled = true;
  2586. if (renameBtn) renameBtn.disabled = true;
  2587. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  2588. } else {
  2589. nameInput.disabled = false;
  2590. if (renameBtn) renameBtn.disabled = false;
  2591. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  2592. }
  2593. }
  2594. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2595. if (iface.is_vlan) {
  2596. delBtn.classList.remove('hidden');
  2597. } else {
  2598. delBtn.classList.add('hidden');
  2599. }
  2600. renderModalIPs(iface);
  2601. document.getElementById('iface-modal').classList.remove('hidden');
  2602. }
  2603. function renderModalIPs(iface) {
  2604. const container = document.getElementById('modal-ip-list');
  2605. container.innerHTML = '';
  2606. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2607. if (addrs.length === 0) {
  2608. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2609. return;
  2610. }
  2611. addrs.forEach(addr => {
  2612. const row = document.createElement('div');
  2613. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2614. row.innerHTML = `
  2615. <span class="text-white">${addr}</span>
  2616. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2617. `;
  2618. container.appendChild(row);
  2619. });
  2620. }
  2621. function closeIfaceModal() {
  2622. document.getElementById('iface-modal').classList.add('hidden');
  2623. state.currentModalIface = null;
  2624. }
  2625. async function setIfaceState(name, newState) {
  2626. const target = name || state.currentModalIface;
  2627. if (!target) return;
  2628. await toggleInterfaceState(target, newState);
  2629. const updated = (state.interfaces || []).find(i => i.name === target);
  2630. if (updated) openIfaceModal(target);
  2631. }
  2632. async function applyMTU() {
  2633. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2634. try {
  2635. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2636. method: 'POST',
  2637. headers: { 'Content-Type': 'application/json' },
  2638. body: JSON.stringify({ mtu })
  2639. });
  2640. if (res.ok) {
  2641. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2642. fetchData(false);
  2643. }
  2644. } catch (err) {
  2645. showToast('Error', err.message, 'error');
  2646. }
  2647. }
  2648. async function addInterfaceIP() {
  2649. const ip = document.getElementById('modal-new-ip').value.trim();
  2650. if (!ip) return;
  2651. try {
  2652. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2653. method: 'POST',
  2654. headers: { 'Content-Type': 'application/json' },
  2655. body: JSON.stringify({ ip })
  2656. });
  2657. if (res.ok) {
  2658. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2659. document.getElementById('modal-new-ip').value = '';
  2660. await fetchData(false);
  2661. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2662. if (iface) renderModalIPs(iface);
  2663. } else {
  2664. const err = await res.json();
  2665. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2666. }
  2667. } catch (err) {
  2668. showToast('Error', err.message, 'error');
  2669. }
  2670. }
  2671. async function removeInterfaceIP(ip) {
  2672. if (!confirm(`Remove IP ${ip}?`)) return;
  2673. try {
  2674. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2675. method: 'DELETE',
  2676. headers: { 'Content-Type': 'application/json' },
  2677. body: JSON.stringify({ ip })
  2678. });
  2679. if (res.ok) {
  2680. showToast('IP Removed', `Removed ${ip}`, 'success');
  2681. await fetchData(false);
  2682. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2683. if (iface) renderModalIPs(iface);
  2684. }
  2685. } catch (err) {
  2686. showToast('Error', err.message, 'error');
  2687. }
  2688. }
  2689. async function renameInterface() {
  2690. const oldName = state.currentModalIface;
  2691. const newNameInput = document.getElementById('modal-iface-new-name');
  2692. const newName = (newNameInput?.value || '').trim();
  2693. if (!oldName) return;
  2694. if (!newName) {
  2695. showToast('Warning', 'Interface name cannot be empty', 'warning');
  2696. return;
  2697. }
  2698. if (newName === oldName) {
  2699. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  2700. return;
  2701. }
  2702. if (newName.length > 15) {
  2703. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  2704. return;
  2705. }
  2706. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  2707. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  2708. return;
  2709. }
  2710. const renameBtn = document.getElementById('modal-btn-rename');
  2711. if (renameBtn) {
  2712. renameBtn.disabled = true;
  2713. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  2714. }
  2715. try {
  2716. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2717. method: 'POST',
  2718. headers: { 'Content-Type': 'application/json' },
  2719. body: JSON.stringify({ new_name: newName })
  2720. });
  2721. const data = await res.json();
  2722. if (!res.ok) {
  2723. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  2724. return;
  2725. }
  2726. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  2727. state.currentModalIface = newName;
  2728. document.getElementById('modal-iface-name').innerText = newName;
  2729. // Refresh application state
  2730. await fetchData(false);
  2731. const updated = (state.interfaces || []).find(i => i.name === newName);
  2732. if (updated) {
  2733. openIfaceModal(newName);
  2734. } else {
  2735. closeIfaceModal();
  2736. }
  2737. } catch (err) {
  2738. showToast('Error', err.message, 'error');
  2739. } finally {
  2740. if (renameBtn) {
  2741. renameBtn.disabled = false;
  2742. renameBtn.innerHTML = `
  2743. <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>
  2744. <span>Rename</span>
  2745. `;
  2746. }
  2747. }
  2748. }
  2749. async function saveInterfaceMetadata() {
  2750. const oldName = state.currentModalIface;
  2751. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  2752. const role = document.getElementById('modal-iface-role').value;
  2753. const desc = document.getElementById('modal-iface-desc').value.trim();
  2754. let targetName = oldName;
  2755. // If user changed the name before clicking Save Changes, execute rename first
  2756. if (newName && newName !== oldName && oldName !== 'lo') {
  2757. try {
  2758. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2759. method: 'POST',
  2760. headers: { 'Content-Type': 'application/json' },
  2761. body: JSON.stringify({ new_name: newName })
  2762. });
  2763. const data = await renameRes.json();
  2764. if (!renameRes.ok) {
  2765. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  2766. return;
  2767. }
  2768. targetName = newName;
  2769. state.currentModalIface = newName;
  2770. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  2771. } catch (err) {
  2772. showToast('Error', err.message, 'error');
  2773. return;
  2774. }
  2775. }
  2776. try {
  2777. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  2778. method: 'POST',
  2779. headers: { 'Content-Type': 'application/json' },
  2780. body: JSON.stringify({ role, description: desc })
  2781. });
  2782. if (res.ok) {
  2783. showToast('Saved', 'Interface configuration updated', 'success');
  2784. closeIfaceModal();
  2785. fetchData(false);
  2786. } else {
  2787. const err = await res.json();
  2788. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  2789. }
  2790. } catch (err) {
  2791. showToast('Error', err.message, 'error');
  2792. }
  2793. }
  2794. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2795. state.fwSubTab = 'filter';
  2796. state.routesSubTab = 'routes';
  2797. function renderRuleFlag(disabled, hasComment) {
  2798. let flags = '';
  2799. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2800. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2801. return flags || '<span class="text-slate-600">-</span>';
  2802. }
  2803. function renderActionBadge(action) {
  2804. const act = (action || '').toLowerCase();
  2805. let color = 'bg-slate-800 text-slate-300';
  2806. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2807. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2808. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2809. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2810. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2811. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2812. }
  2813. function switchFWSubTab(tab) {
  2814. state.fwSubTab = tab;
  2815. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2816. tabs.forEach(t => {
  2817. const panel = document.getElementById(`fw-subtab-${t}`);
  2818. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2819. if (panel) {
  2820. if (t === tab) panel.classList.remove('hidden');
  2821. else panel.classList.add('hidden');
  2822. }
  2823. if (btn) {
  2824. if (t === tab) {
  2825. 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';
  2826. } else {
  2827. 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';
  2828. }
  2829. }
  2830. });
  2831. const addBtn = document.getElementById('fw-primary-add-btn');
  2832. if (addBtn) {
  2833. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2834. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2835. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2836. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2837. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2838. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2839. }
  2840. if (tab === 'geo') loadGeoIP();
  2841. if (tab === 'connections') loadConnections();
  2842. setTimeout(initTableSorting, 50);
  2843. }
  2844. function openCurrentFWModal() {
  2845. if (state.fwSubTab === 'filter') openAddFilterModal();
  2846. else if (state.fwSubTab === 'nat') openAddNATModal();
  2847. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2848. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2849. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2850. else if (state.fwSubTab === 'connections') loadConnections();
  2851. }
  2852. async function loadFirewall(populateDropdowns = true) {
  2853. try {
  2854. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2855. fetch(`${API_BASE}/firewall/summary`),
  2856. fetch(`${API_BASE}/firewall/filter`),
  2857. fetch(`${API_BASE}/firewall/nat`),
  2858. fetch(`${API_BASE}/firewall/mangle`),
  2859. fetch(`${API_BASE}/firewall/address-lists`),
  2860. fetch(`${API_BASE}/firewall/geoip/status`),
  2861. fetch(`${API_BASE}/firewall/geoip/countries`)
  2862. ]);
  2863. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2864. if (filterRes.ok) state.filterRules = await filterRes.json();
  2865. if (natRes.ok) state.natRules = await natRes.json();
  2866. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2867. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2868. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2869. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2870. // Badges
  2871. const bFilter = document.getElementById('fw-badge-filter');
  2872. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2873. const bNat = document.getElementById('fw-badge-nat');
  2874. if (bNat) bNat.innerText = (state.natRules || []).length;
  2875. const bMangle = document.getElementById('fw-badge-mangle');
  2876. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2877. const bAddr = document.getElementById('fw-badge-addrlist');
  2878. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2879. const bGeo = document.getElementById('fw-badge-geo');
  2880. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2881. renderFilterRules();
  2882. renderNATRules();
  2883. renderMangleRules();
  2884. renderAddressLists();
  2885. renderGeoCountries();
  2886. if (state.fwSubTab === 'connections') {
  2887. loadConnections();
  2888. }
  2889. } catch (err) {
  2890. console.error('Failed to load firewall:', err);
  2891. }
  2892. }
  2893. // ----------------- Filter Rules -----------------
  2894. function renderFilterRules() {
  2895. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2896. const tbody = document.getElementById('filter-table-body');
  2897. const empty = document.getElementById('filter-empty');
  2898. if (!tbody) return;
  2899. tbody.innerHTML = '';
  2900. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2901. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2902. if (rules.length === 0) {
  2903. empty?.classList.remove('hidden');
  2904. return;
  2905. }
  2906. empty?.classList.add('hidden');
  2907. rules.forEach((r, idx) => {
  2908. const tr = document.createElement('tr');
  2909. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2910. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2911. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2912. let actionExtra = '';
  2913. if (r.action === 'reject') {
  2914. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2915. } else if (r.action === 'jump') {
  2916. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2917. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2918. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2919. } else if (r.action === 'log' && r.log_prefix) {
  2920. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2921. }
  2922. tr.innerHTML = `
  2923. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2924. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2925. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2926. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2927. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2928. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2929. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2930. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2931. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2932. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2933. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2934. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2935. </td>
  2936. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2937. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2938. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2939. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2940. <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>
  2941. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2942. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2943. </td>
  2944. `;
  2945. tbody.appendChild(tr);
  2946. });
  2947. }
  2948. function formatTarget(addr, list, geo) {
  2949. const parts = [];
  2950. if (addr) parts.push(`<span>${addr}</span>`);
  2951. if (list) {
  2952. const inv = list.startsWith('!') ? '!' : '';
  2953. const clean = list.replace(/^!/, '');
  2954. 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>`);
  2955. }
  2956. if (geo) {
  2957. const inv = geo.startsWith('!') ? '!' : '';
  2958. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2959. 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>`);
  2960. }
  2961. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2962. return parts.join(' ');
  2963. }
  2964. function populateInterfaceSelect(selectId, currentVal = '') {
  2965. const sel = document.getElementById(selectId);
  2966. if (!sel) return;
  2967. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2968. (state.interfaces || []).forEach(i => {
  2969. const opt = document.createElement('option');
  2970. opt.value = i.name;
  2971. opt.innerText = `${i.name} (${i.role || i.type})`;
  2972. if (i.name === currentVal) opt.selected = true;
  2973. sel.appendChild(opt);
  2974. });
  2975. }
  2976. function populateAddressListSelect(selectId, currentVal = '') {
  2977. const sel = document.getElementById(selectId);
  2978. if (!sel) return;
  2979. sel.innerHTML = '<option value="">(None)</option>';
  2980. const cleanVal = (currentVal || '').replace(/^!/, '');
  2981. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2982. customNames.forEach(name => {
  2983. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2984. const opt = document.createElement('option');
  2985. opt.value = name;
  2986. opt.innerText = `${name} (${count} entries)`;
  2987. if (name === cleanVal) opt.selected = true;
  2988. sel.appendChild(opt);
  2989. });
  2990. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2991. const opt = document.createElement('option');
  2992. opt.value = cleanVal;
  2993. opt.innerText = cleanVal;
  2994. opt.selected = true;
  2995. sel.appendChild(opt);
  2996. }
  2997. populateCommonAddrListDatalist();
  2998. }
  2999. function populateCommonAddrListDatalist() {
  3000. const dl = document.getElementById('fw-addrlist-datalist');
  3001. if (!dl) return;
  3002. dl.innerHTML = '';
  3003. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3004. names.forEach(name => {
  3005. const opt = document.createElement('option');
  3006. opt.value = name;
  3007. dl.appendChild(opt);
  3008. });
  3009. }
  3010. function populateGeoIPSelect(selectId, currentVal = '') {
  3011. const sel = document.getElementById(selectId);
  3012. if (!sel) return;
  3013. sel.innerHTML = '<option value="">(None)</option>';
  3014. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3015. // Presets optgroup
  3016. const grpPresets = document.createElement('optgroup');
  3017. grpPresets.label = '⚡ Regional Presets';
  3018. const presets = [
  3019. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3020. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3021. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3022. ];
  3023. presets.forEach(p => {
  3024. const opt = document.createElement('option');
  3025. opt.value = p.code;
  3026. opt.innerText = p.label;
  3027. if (p.code === cleanVal) opt.selected = true;
  3028. grpPresets.appendChild(opt);
  3029. });
  3030. sel.appendChild(grpPresets);
  3031. // All Countries optgroup
  3032. const grpCountries = document.createElement('optgroup');
  3033. grpCountries.label = '🌍 All Countries';
  3034. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3035. countries.forEach(c => {
  3036. const opt = document.createElement('option');
  3037. opt.value = c.code;
  3038. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3039. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3040. if (c.code === cleanVal) opt.selected = true;
  3041. grpCountries.appendChild(opt);
  3042. });
  3043. sel.appendChild(grpCountries);
  3044. }
  3045. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3046. function switchFwRuleTab(tab) {
  3047. state.activeFwRuleTab = tab;
  3048. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3049. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3050. btn.classList.add('text-slate-400', 'border-transparent');
  3051. });
  3052. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3053. if (activeBtn) {
  3054. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3055. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3056. }
  3057. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3058. const activePane = document.getElementById(`fw-pane-${tab}`);
  3059. if (activePane) activePane.classList.remove('hidden');
  3060. if (tab === 'statistics') {
  3061. startFwStatPolling();
  3062. } else {
  3063. stopFwStatPolling();
  3064. }
  3065. }
  3066. function toggleFwField(fieldKey, expand) {
  3067. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3068. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3069. if (!plusBtn || !fieldBox) return;
  3070. if (expand) {
  3071. plusBtn.classList.add('hidden');
  3072. fieldBox.classList.remove('hidden');
  3073. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3074. if (valInput) valInput.focus();
  3075. } else {
  3076. fieldBox.classList.add('hidden');
  3077. plusBtn.classList.remove('hidden');
  3078. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3079. if (valInput) {
  3080. if (valInput.tagName === 'SELECT') {
  3081. valInput.selectedIndex = 0;
  3082. } else {
  3083. valInput.value = '';
  3084. }
  3085. }
  3086. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3087. if (invInput) invInput.checked = false;
  3088. if (fieldKey === 'cs') {
  3089. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3090. const el = document.getElementById(id);
  3091. if (el) el.checked = false;
  3092. });
  3093. }
  3094. if (fieldKey === 'natstate') {
  3095. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3096. const el = document.getElementById(id);
  3097. if (el) el.checked = false;
  3098. });
  3099. }
  3100. if (fieldKey === 'days') {
  3101. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3102. const el = document.getElementById(`fw-day-${d}`);
  3103. if (el) el.checked = true;
  3104. });
  3105. }
  3106. }
  3107. }
  3108. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3109. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3110. toggleFwField(fieldKey, true);
  3111. let strVal = String(value);
  3112. if (hasInvert) {
  3113. const inv = strVal.startsWith('!');
  3114. if (inv) strVal = strVal.slice(1);
  3115. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3116. if (invEl) invEl.checked = inv;
  3117. }
  3118. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3119. if (valEl) valEl.value = strVal;
  3120. } else {
  3121. toggleFwField(fieldKey, false);
  3122. }
  3123. }
  3124. function getFwFieldVal(fieldKey, hasInvert = false) {
  3125. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3126. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3127. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3128. let v = valEl ? valEl.value.trim() : '';
  3129. if (!v) return '';
  3130. if (hasInvert) {
  3131. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3132. if (invEl && invEl.checked) {
  3133. v = '!' + v.replace(/^!/, '');
  3134. }
  3135. }
  3136. return v;
  3137. }
  3138. function toggleMaximizeFilterModal() {
  3139. const win = document.getElementById('filter-modal-window');
  3140. if (!win) return;
  3141. if (win.classList.contains('max-w-[720px]')) {
  3142. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3143. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3144. } else {
  3145. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3146. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3147. }
  3148. }
  3149. function openAddFilterModal() {
  3150. switchFwRuleTab('general');
  3151. const badge = document.getElementById('fw-modal-badge');
  3152. if (badge) badge.innerText = 'New...';
  3153. document.getElementById('filter-modal-id').value = '';
  3154. document.getElementById('filter-modal-enabled').checked = true;
  3155. document.getElementById('filter-modal-comment').value = '';
  3156. document.getElementById('filter-modal-chain').value = 'forward';
  3157. document.getElementById('filter-modal-action').value = 'accept';
  3158. document.getElementById('filter-modal-log').checked = false;
  3159. populateInterfaceSelect('fw-val-iniface');
  3160. populateInterfaceSelect('fw-val-outiface');
  3161. populateAddressListSelect('fw-val-srclist');
  3162. populateAddressListSelect('fw-val-dstlist');
  3163. populateGeoIPSelect('fw-val-srcgeo');
  3164. populateGeoIPSelect('fw-val-dstgeo');
  3165. const allFieldKeys = [
  3166. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3167. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3168. 'routingmark', 'conntype', 'cs', 'natstate',
  3169. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3170. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3171. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3172. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3173. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3174. ];
  3175. allFieldKeys.forEach(k => toggleFwField(k, false));
  3176. resetCurrentRuleCounters();
  3177. toggleFilterActionFields();
  3178. document.getElementById('filter-modal').classList.remove('hidden');
  3179. }
  3180. function openEditFilterModal(id) {
  3181. const r = (state.filterRules || []).find(rule => rule.id === id);
  3182. if (!r) return;
  3183. switchFwRuleTab('general');
  3184. const badge = document.getElementById('fw-modal-badge');
  3185. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3186. document.getElementById('filter-modal-id').value = r.id;
  3187. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3188. document.getElementById('filter-modal-comment').value = r.comment || '';
  3189. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3190. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3191. document.getElementById('filter-modal-log').checked = !!r.log;
  3192. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3193. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3194. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3195. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3196. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3197. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3198. setFwFieldVal('src', r.src_address, true);
  3199. setFwFieldVal('dst', r.dst_address, true);
  3200. setFwFieldVal('srclist', r.src_address_list, true);
  3201. setFwFieldVal('dstlist', r.dst_address_list, true);
  3202. setFwFieldVal('srcgeo', r.src_geoip, true);
  3203. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3204. if (r.protocol && r.protocol !== 'all') {
  3205. setFwFieldVal('proto', r.protocol, true);
  3206. } else {
  3207. toggleFwField('proto', false);
  3208. }
  3209. setFwFieldVal('sport', r.src_port, true);
  3210. setFwFieldVal('dport', r.dst_port, true);
  3211. setFwFieldVal('anyport', r.any_port, true);
  3212. setFwFieldVal('iniface', r.in_interface, true);
  3213. setFwFieldVal('outiface', r.out_interface, true);
  3214. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3215. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3216. setFwFieldVal('pktmark', r.packet_mark, true);
  3217. setFwFieldVal('connmark', r.connection_mark, true);
  3218. setFwFieldVal('routingmark', r.routing_mark, true);
  3219. setFwFieldVal('conntype', r.connection_type, false);
  3220. const states = r.connection_state || [];
  3221. if (states.length > 0) {
  3222. toggleFwField('cs', true);
  3223. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3224. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3225. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3226. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3227. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3228. } else {
  3229. toggleFwField('cs', false);
  3230. }
  3231. const natStates = r.connection_nat_state || [];
  3232. if (natStates.length > 0) {
  3233. toggleFwField('natstate', true);
  3234. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3235. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3236. } else {
  3237. toggleFwField('natstate', false);
  3238. }
  3239. // Advanced tab fields
  3240. setFwFieldVal('layer7', r.layer7_protocol, false);
  3241. setFwFieldVal('content', r.content, false);
  3242. setFwFieldVal('connbytes', r.connection_bytes, false);
  3243. setFwFieldVal('connrate', r.connection_rate, false);
  3244. setFwFieldVal('pcc', r.pcc, false);
  3245. setFwFieldVal('srcmac', r.src_mac_address, true);
  3246. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3247. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3248. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3249. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3250. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3251. setFwFieldVal('tlshost', r.tls_host, false);
  3252. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3253. setFwFieldVal('priority', r.priority, false);
  3254. setFwFieldVal('dscp', r.dscp, false);
  3255. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3256. if (r.tos) {
  3257. const tosEl = document.getElementById('fw-val-tos');
  3258. if (tosEl) tosEl.value = r.tos;
  3259. }
  3260. setFwFieldVal('pktsize', r.packet_size, false);
  3261. setFwFieldVal('random', r.random, false);
  3262. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3263. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3264. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3265. setFwFieldVal('ttl', r.ttl, false);
  3266. // Extra tab fields
  3267. setFwFieldVal('time', r.time, false);
  3268. if (r.days) {
  3269. toggleFwField('days', true);
  3270. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3271. const chk = document.getElementById(`fw-day-${d}`);
  3272. if (chk) chk.checked = r.days.includes(d);
  3273. });
  3274. } else {
  3275. toggleFwField('days', false);
  3276. }
  3277. setFwFieldVal('limit', r.limit, false);
  3278. setFwFieldVal('dstlimit', r.dst_limit, false);
  3279. setFwFieldVal('psd', r.psd, false);
  3280. // Action fields
  3281. if (r.reject_with) {
  3282. const rwEl = document.getElementById('filter-modal-rejectwith');
  3283. if (rwEl) rwEl.value = r.reject_with;
  3284. }
  3285. if (r.jump_target) {
  3286. const jtEl = document.getElementById('filter-modal-jumptarget');
  3287. if (jtEl) jtEl.value = r.jump_target;
  3288. }
  3289. if (r.address_list) {
  3290. const alEl = document.getElementById('filter-modal-action-addrlist');
  3291. if (alEl) alEl.value = r.address_list;
  3292. }
  3293. if (r.address_list_timeout) {
  3294. const toEl = document.getElementById('filter-modal-action-timeout');
  3295. if (toEl) toEl.value = r.address_list_timeout;
  3296. }
  3297. setFwFieldVal('logprefix', r.log_prefix, false);
  3298. // Statistics
  3299. const bEl = document.getElementById('fw-stat-bytes');
  3300. const pEl = document.getElementById('fw-stat-packets');
  3301. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3302. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3303. state.fwLastBytes = r.bytes || 0;
  3304. state.fwLastPackets = r.packets || 0;
  3305. state.fwLastTimestamp = Date.now();
  3306. state.fwStatRateHistory = new Array(30).fill(0);
  3307. state.fwStatPktHistory = new Array(30).fill(0);
  3308. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3309. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3310. toggleFilterActionFields();
  3311. document.getElementById('filter-modal').classList.remove('hidden');
  3312. }
  3313. function closeFilterModal() {
  3314. stopFwStatPolling();
  3315. document.getElementById('filter-modal').classList.add('hidden');
  3316. }
  3317. function toggleFilterActionFields() {
  3318. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3319. const rejectBox = document.getElementById('filter-action-reject-box');
  3320. const jumpBox = document.getElementById('filter-action-jump-box');
  3321. const addrBox = document.getElementById('filter-action-addrlist-box');
  3322. if (rejectBox) {
  3323. if (act === 'reject') rejectBox.classList.remove('hidden');
  3324. else rejectBox.classList.add('hidden');
  3325. }
  3326. if (jumpBox) {
  3327. if (act === 'jump') jumpBox.classList.remove('hidden');
  3328. else jumpBox.classList.add('hidden');
  3329. }
  3330. if (addrBox) {
  3331. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3332. addrBox.classList.remove('hidden');
  3333. } else {
  3334. addrBox.classList.add('hidden');
  3335. }
  3336. }
  3337. if (act === 'log') {
  3338. const logEl = document.getElementById('filter-modal-log');
  3339. if (logEl) logEl.checked = true;
  3340. toggleFwField('logprefix', true);
  3341. }
  3342. }
  3343. function toggleFwLogPrefix() {
  3344. const isLog = document.getElementById('filter-modal-log')?.checked;
  3345. toggleFwField('logprefix', !!isLog);
  3346. }
  3347. function copyFilterRule() {
  3348. document.getElementById('filter-modal-id').value = '';
  3349. const badge = document.getElementById('fw-modal-badge');
  3350. if (badge) badge.innerText = 'New...';
  3351. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3352. }
  3353. function resetCurrentRuleCounters() {
  3354. state.fwStatRateHistory = new Array(30).fill(0);
  3355. state.fwStatPktHistory = new Array(30).fill(0);
  3356. state.fwLastBytes = 0;
  3357. state.fwLastPackets = 0;
  3358. state.fwLastTimestamp = Date.now();
  3359. const bEl = document.getElementById('fw-stat-bytes');
  3360. const pEl = document.getElementById('fw-stat-packets');
  3361. const rEl = document.getElementById('fw-stat-rate');
  3362. const prEl = document.getElementById('fw-stat-pktrate');
  3363. if (bEl) bEl.value = '0 B';
  3364. if (pEl) pEl.value = '0';
  3365. if (rEl) rEl.value = '0 bps';
  3366. if (prEl) prEl.value = '0 p/s';
  3367. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3368. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3369. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3370. }
  3371. async function resetAllFwCounters() {
  3372. try {
  3373. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3374. if (res.ok) {
  3375. resetCurrentRuleCounters();
  3376. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3377. loadFirewall(false);
  3378. }
  3379. } catch (err) {
  3380. showToast('Error', err.message, 'error');
  3381. }
  3382. }
  3383. async function applyFilterRule(closeAfter = false) {
  3384. const id = document.getElementById('filter-modal-id').value;
  3385. const chain = document.getElementById('filter-modal-chain').value;
  3386. const action = document.getElementById('filter-modal-action').value;
  3387. const comment = document.getElementById('filter-modal-comment').value.trim();
  3388. const enabled = document.getElementById('filter-modal-enabled').checked;
  3389. const src = getFwFieldVal('src', true);
  3390. const dst = getFwFieldVal('dst', true);
  3391. const srclist = getFwFieldVal('srclist', true);
  3392. const dstlist = getFwFieldVal('dstlist', true);
  3393. const srcgeo = getFwFieldVal('srcgeo', true);
  3394. const dstgeo = getFwFieldVal('dstgeo', true);
  3395. const proto = getFwFieldVal('proto', true);
  3396. const sport = getFwFieldVal('sport', true);
  3397. const dport = getFwFieldVal('dport', true);
  3398. const anyport = getFwFieldVal('anyport', true);
  3399. const iniface = getFwFieldVal('iniface', true);
  3400. const outiface = getFwFieldVal('outiface', true);
  3401. const inifacelist = getFwFieldVal('inifacelist', true);
  3402. const outifacelist = getFwFieldVal('outifacelist', true);
  3403. const pktmark = getFwFieldVal('pktmark', true);
  3404. const connmark = getFwFieldVal('connmark', true);
  3405. const routingmark = getFwFieldVal('routingmark', true);
  3406. const conntype = getFwFieldVal('conntype', false);
  3407. const states = [];
  3408. const csBox = document.getElementById('fw-field-cs');
  3409. if (csBox && !csBox.classList.contains('hidden')) {
  3410. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3411. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3412. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3413. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3414. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3415. }
  3416. const natStates = [];
  3417. const natBox = document.getElementById('fw-field-natstate');
  3418. if (natBox && !natBox.classList.contains('hidden')) {
  3419. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3420. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3421. }
  3422. const payload = {
  3423. id,
  3424. chain,
  3425. action,
  3426. protocol: proto || 'all',
  3427. src_address: src,
  3428. dst_address: dst,
  3429. src_port: sport,
  3430. dst_port: dport,
  3431. any_port: anyport,
  3432. in_interface: iniface,
  3433. out_interface: outiface,
  3434. in_interface_list: inifacelist,
  3435. out_interface_list: outifacelist,
  3436. packet_mark: pktmark,
  3437. connection_mark: connmark,
  3438. routing_mark: routingmark,
  3439. connection_type: conntype,
  3440. connection_state: states,
  3441. connection_nat_state: natStates,
  3442. src_address_list: srclist,
  3443. dst_address_list: dstlist,
  3444. src_geoip: srcgeo,
  3445. dst_geoip: dstgeo,
  3446. comment,
  3447. disabled: !enabled,
  3448. // Advanced tab
  3449. layer7_protocol: getFwFieldVal('layer7', false),
  3450. content: getFwFieldVal('content', false),
  3451. connection_bytes: getFwFieldVal('connbytes', false),
  3452. connection_rate: getFwFieldVal('connrate', false),
  3453. pcc: getFwFieldVal('pcc', false),
  3454. src_mac_address: getFwFieldVal('srcmac', true),
  3455. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3456. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3457. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3458. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3459. ipsec_policy: getFwFieldVal('ipsec', false),
  3460. tls_host: getFwFieldVal('tlshost', false),
  3461. ingress_priority: getFwFieldVal('ingresspriority', false),
  3462. priority: getFwFieldVal('priority', false),
  3463. dscp: getFwFieldVal('dscp', false),
  3464. tcp_mss: getFwFieldVal('tcpmss', false),
  3465. tos: document.getElementById('fw-val-tos')?.value || '',
  3466. packet_size: getFwFieldVal('pktsize', false),
  3467. random: getFwFieldVal('random', false),
  3468. tcp_flags: getFwFieldVal('tcpflags', false),
  3469. icmp_options: getFwFieldVal('icmpoptions', false),
  3470. ipv4_options: getFwFieldVal('ipv4options', false),
  3471. ttl: getFwFieldVal('ttl', false),
  3472. // Extra tab
  3473. time: getFwFieldVal('time', false),
  3474. limit: getFwFieldVal('limit', false),
  3475. dst_limit: getFwFieldVal('dstlimit', false),
  3476. psd: getFwFieldVal('psd', false),
  3477. // Action tab
  3478. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3479. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3480. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3481. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3482. log: document.getElementById('filter-modal-log')?.checked || false,
  3483. log_prefix: getFwFieldVal('logprefix', false)
  3484. };
  3485. try {
  3486. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3487. method: 'POST',
  3488. headers: { 'Content-Type': 'application/json' },
  3489. body: JSON.stringify(payload)
  3490. });
  3491. if (res.ok) {
  3492. const data = await res.json();
  3493. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3494. loadFirewall(false);
  3495. if (closeAfter) {
  3496. closeFilterModal();
  3497. } else {
  3498. if (data.id) {
  3499. document.getElementById('filter-modal-id').value = data.id;
  3500. const badge = document.getElementById('fw-modal-badge');
  3501. if (badge) badge.innerText = `#${data.id}`;
  3502. }
  3503. }
  3504. } else {
  3505. const err = await res.json();
  3506. showToast('Error', err.message || 'Failed to save rule', 'error');
  3507. }
  3508. } catch (err) {
  3509. showToast('Error', err.message, 'error');
  3510. }
  3511. }
  3512. function submitSaveFilterRule(e) {
  3513. if (e && e.preventDefault) e.preventDefault();
  3514. return applyFilterRule(true);
  3515. }
  3516. function startFwStatPolling() {
  3517. stopFwStatPolling();
  3518. pollRuleStats();
  3519. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3520. }
  3521. function stopFwStatPolling() {
  3522. if (state.fwStatInterval) {
  3523. clearInterval(state.fwStatInterval);
  3524. state.fwStatInterval = null;
  3525. }
  3526. }
  3527. async function pollRuleStats() {
  3528. const id = document.getElementById('filter-modal-id')?.value;
  3529. if (!id) {
  3530. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3531. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3532. return;
  3533. }
  3534. try {
  3535. const res = await fetch(`${API_BASE}/firewall/filter`);
  3536. if (!res.ok) return;
  3537. const rules = await res.json();
  3538. const r = rules.find(x => x.id === id);
  3539. if (!r) return;
  3540. const now = Date.now();
  3541. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3542. state.fwLastTimestamp = now;
  3543. const curBytes = r.bytes || 0;
  3544. const curPackets = r.packets || 0;
  3545. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3546. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3547. state.fwLastBytes = curBytes;
  3548. state.fwLastPackets = curPackets;
  3549. const rateBps = Math.round((deltaBytes * 8) / dt);
  3550. const ratePkt = Math.round(deltaPkts / dt);
  3551. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3552. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3553. state.fwStatRateHistory.push(rateBps);
  3554. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3555. state.fwStatPktHistory.push(ratePkt);
  3556. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3557. const bEl = document.getElementById('fw-stat-bytes');
  3558. const pEl = document.getElementById('fw-stat-packets');
  3559. const rEl = document.getElementById('fw-stat-rate');
  3560. const prEl = document.getElementById('fw-stat-pktrate');
  3561. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3562. if (pEl) pEl.value = curPackets.toLocaleString();
  3563. if (rEl) rEl.value = formatBps(rateBps);
  3564. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3565. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3566. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3567. } catch (e) {
  3568. console.error('Error polling rule stats', e);
  3569. }
  3570. }
  3571. function formatBps(bps) {
  3572. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3573. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3574. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3575. return bps + ' bps';
  3576. }
  3577. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3578. const svg = document.getElementById(svgId);
  3579. if (!svg) return;
  3580. const w = 500;
  3581. const h = 100;
  3582. const paddingRight = 45;
  3583. const graphWidth = w - paddingRight;
  3584. const maxVal = Math.max(5, ...dataArray);
  3585. const currentVal = dataArray[dataArray.length - 1] || 0;
  3586. const leg = document.getElementById(legendId);
  3587. if (leg) {
  3588. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3589. }
  3590. let gridLines = '';
  3591. for (let i = 0; i <= 5; i++) {
  3592. const y = 8 + (i * (h - 18) / 5);
  3593. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3594. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3595. gridLines += `
  3596. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3597. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3598. `;
  3599. }
  3600. const step = graphWidth / (dataArray.length - 1);
  3601. const points = dataArray.map((val, idx) => {
  3602. const x = idx * step;
  3603. const y = (h - 10) - (val / maxVal) * (h - 20);
  3604. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3605. });
  3606. const polylineStr = points.join(' ');
  3607. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3608. svg.innerHTML = `
  3609. ${gridLines}
  3610. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3611. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3612. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3613. `;
  3614. }
  3615. async function moveFilterRule(id, dir) {
  3616. try {
  3617. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3618. method: 'POST',
  3619. headers: { 'Content-Type': 'application/json' },
  3620. body: JSON.stringify({ direction: dir })
  3621. });
  3622. if (res.ok) loadFirewall(false);
  3623. } catch (err) {
  3624. showToast('Error', err.message, 'error');
  3625. }
  3626. }
  3627. async function toggleFilterRuleState(id, disabled) {
  3628. try {
  3629. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3630. method: 'POST',
  3631. headers: { 'Content-Type': 'application/json' },
  3632. body: JSON.stringify({ disabled })
  3633. });
  3634. if (res.ok) loadFirewall(false);
  3635. } catch (err) {
  3636. showToast('Error', err.message, 'error');
  3637. }
  3638. }
  3639. async function deleteFilterRule(id) {
  3640. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3641. try {
  3642. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3643. if (res.ok) {
  3644. showToast('Deleted', 'Filter rule removed', 'success');
  3645. loadFirewall(false);
  3646. }
  3647. } catch (err) {
  3648. showToast('Error', err.message, 'error');
  3649. }
  3650. }
  3651. // ----------------- NAT Rules -----------------
  3652. function renderNATRules() {
  3653. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3654. const tbody = document.getElementById('nat-table-body');
  3655. const empty = document.getElementById('nat-empty');
  3656. if (!tbody) return;
  3657. tbody.innerHTML = '';
  3658. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3659. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3660. if (rules.length === 0) {
  3661. empty?.classList.remove('hidden');
  3662. return;
  3663. }
  3664. empty?.classList.add('hidden');
  3665. rules.forEach((r, idx) => {
  3666. const tr = document.createElement('tr');
  3667. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3668. let toTarget = '-';
  3669. if (r.action === 'jump') {
  3670. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3671. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3672. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3673. } else if (r.action === 'redirect') {
  3674. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3675. } else if (r.action === 'masquerade') {
  3676. 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>`;
  3677. } else if (r.action === 'log') {
  3678. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3679. } else {
  3680. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3681. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3682. }
  3683. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3684. tr.innerHTML = `
  3685. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3686. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3687. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3688. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3689. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3690. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3691. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3692. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3693. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3694. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3695. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3696. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3697. </td>
  3698. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3699. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3700. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3701. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3702. <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>
  3703. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3704. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3705. </td>
  3706. `;
  3707. tbody.appendChild(tr);
  3708. });
  3709. }
  3710. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3711. function switchNATRuleTab(tab) {
  3712. state.activeNATRuleTab = tab;
  3713. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3714. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3715. btn.classList.add('text-slate-400', 'border-transparent');
  3716. });
  3717. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3718. if (activeBtn) {
  3719. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3720. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3721. }
  3722. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3723. const activePane = document.getElementById(`nat-pane-${tab}`);
  3724. if (activePane) activePane.classList.remove('hidden');
  3725. if (tab === 'statistics') {
  3726. startNATStatPolling();
  3727. } else {
  3728. stopNATStatPolling();
  3729. }
  3730. }
  3731. function toggleNATField(fieldKey, expand) {
  3732. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3733. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3734. if (!plusBtn || !fieldBox) return;
  3735. if (expand) {
  3736. plusBtn.classList.add('hidden');
  3737. fieldBox.classList.remove('hidden');
  3738. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3739. if (valInput) valInput.focus();
  3740. } else {
  3741. fieldBox.classList.add('hidden');
  3742. plusBtn.classList.remove('hidden');
  3743. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3744. if (valInput) {
  3745. if (valInput.tagName === 'SELECT') {
  3746. valInput.selectedIndex = 0;
  3747. } else {
  3748. valInput.value = '';
  3749. }
  3750. }
  3751. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3752. if (invInput) invInput.checked = false;
  3753. if (fieldKey === 'days') {
  3754. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3755. const el = document.getElementById(`nat-day-${d}`);
  3756. if (el) el.checked = true;
  3757. });
  3758. }
  3759. }
  3760. }
  3761. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3762. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3763. toggleNATField(fieldKey, true);
  3764. let strVal = String(value);
  3765. if (hasInvert) {
  3766. const inv = strVal.startsWith('!');
  3767. if (inv) strVal = strVal.slice(1);
  3768. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3769. if (invEl) invEl.checked = inv;
  3770. }
  3771. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3772. if (valEl) valEl.value = strVal;
  3773. } else {
  3774. toggleNATField(fieldKey, false);
  3775. }
  3776. }
  3777. function getNATFieldVal(fieldKey, hasInvert = false) {
  3778. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3779. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3780. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3781. let v = valEl ? valEl.value.trim() : '';
  3782. if (!v) return '';
  3783. if (hasInvert) {
  3784. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3785. if (invEl && invEl.checked) {
  3786. v = '!' + v.replace(/^!/, '');
  3787. }
  3788. }
  3789. return v;
  3790. }
  3791. function toggleMaximizeNATModal() {
  3792. const win = document.getElementById('nat-modal-window');
  3793. if (!win) return;
  3794. if (win.classList.contains('max-w-[720px]')) {
  3795. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3796. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3797. } else {
  3798. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3799. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3800. }
  3801. }
  3802. function handleNATChainChange() {
  3803. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3804. const actSel = document.getElementById('nat-modal-action');
  3805. if (actSel) {
  3806. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3807. actSel.value = 'masquerade';
  3808. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3809. actSel.value = 'dst-nat';
  3810. }
  3811. }
  3812. toggleNATActionFields();
  3813. }
  3814. function toggleNATActionFields() {
  3815. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3816. const rowAddr = document.getElementById('nat-row-toaddr');
  3817. const rowPort = document.getElementById('nat-row-toport');
  3818. const jumpBox = document.getElementById('nat-action-jump-box');
  3819. const addrBox = document.getElementById('nat-action-addrlist-box');
  3820. // Hide all dynamic rows first
  3821. if (rowAddr) rowAddr.classList.add('hidden');
  3822. if (rowPort) rowPort.classList.add('hidden');
  3823. if (jumpBox) jumpBox.classList.add('hidden');
  3824. if (addrBox) addrBox.classList.add('hidden');
  3825. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3826. if (rowAddr) rowAddr.classList.remove('hidden');
  3827. if (rowPort) rowPort.classList.remove('hidden');
  3828. } else if (act === 'redirect' || act === 'masquerade') {
  3829. if (rowPort) rowPort.classList.remove('hidden');
  3830. } else if (act === 'jump') {
  3831. if (jumpBox) jumpBox.classList.remove('hidden');
  3832. } else if (act.includes('address-list') || act.includes('address list')) {
  3833. if (addrBox) addrBox.classList.remove('hidden');
  3834. }
  3835. if (act === 'log') {
  3836. const logEl = document.getElementById('nat-modal-log');
  3837. if (logEl) logEl.checked = true;
  3838. toggleNATField('logprefix', true);
  3839. }
  3840. }
  3841. function toggleNATLogPrefix() {
  3842. const isLog = document.getElementById('nat-modal-log')?.checked;
  3843. toggleNATField('logprefix', !!isLog);
  3844. }
  3845. function openAddNATModal() {
  3846. switchNATRuleTab('general');
  3847. const badge = document.getElementById('nat-modal-badge');
  3848. if (badge) badge.innerText = 'New...';
  3849. document.getElementById('nat-modal-id').value = '';
  3850. document.getElementById('nat-modal-enabled').checked = true;
  3851. document.getElementById('nat-modal-comment').value = '';
  3852. document.getElementById('nat-modal-chain').value = 'srcnat';
  3853. document.getElementById('nat-modal-action').value = 'masquerade';
  3854. document.getElementById('nat-modal-toaddr').value = '';
  3855. document.getElementById('nat-modal-toport').value = '';
  3856. document.getElementById('nat-modal-log').checked = false;
  3857. populateInterfaceSelect('nat-val-iniface');
  3858. populateInterfaceSelect('nat-val-outiface');
  3859. populateAddressListSelect('nat-val-srclist');
  3860. populateAddressListSelect('nat-val-dstlist');
  3861. populateGeoIPSelect('nat-val-srcgeo');
  3862. populateGeoIPSelect('nat-val-dstgeo');
  3863. const allFieldKeys = [
  3864. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3865. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3866. 'routingmark', 'conntype',
  3867. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3868. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3869. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3870. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3871. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3872. ];
  3873. allFieldKeys.forEach(k => toggleNATField(k, false));
  3874. resetCurrentNATRuleCounters();
  3875. toggleNATActionFields();
  3876. document.getElementById('nat-modal').classList.remove('hidden');
  3877. }
  3878. function openEditNATModal(id) {
  3879. const r = (state.natRules || []).find(rule => rule.id === id);
  3880. if (!r) return;
  3881. switchNATRuleTab('general');
  3882. const badge = document.getElementById('nat-modal-badge');
  3883. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3884. document.getElementById('nat-modal-id').value = r.id;
  3885. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3886. document.getElementById('nat-modal-comment').value = r.comment || '';
  3887. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3888. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3889. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3890. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3891. document.getElementById('nat-modal-log').checked = !!r.log;
  3892. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3893. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3894. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3895. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3896. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3897. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3898. setNATFieldVal('src', r.src_address, true);
  3899. setNATFieldVal('dst', r.dst_address, true);
  3900. setNATFieldVal('srclist', r.src_address_list, true);
  3901. setNATFieldVal('dstlist', r.dst_address_list, true);
  3902. setNATFieldVal('srcgeo', r.src_geoip, true);
  3903. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3904. if (r.protocol && r.protocol !== 'all') {
  3905. setNATFieldVal('proto', r.protocol, true);
  3906. } else {
  3907. toggleNATField('proto', false);
  3908. }
  3909. setNATFieldVal('sport', r.src_port, true);
  3910. setNATFieldVal('dport', r.dst_port, true);
  3911. setNATFieldVal('anyport', r.any_port, true);
  3912. setNATFieldVal('iniface', r.in_interface, true);
  3913. setNATFieldVal('outiface', r.out_interface, true);
  3914. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3915. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3916. setNATFieldVal('pktmark', r.packet_mark, true);
  3917. setNATFieldVal('connmark', r.connection_mark, true);
  3918. setNATFieldVal('routingmark', r.routing_mark, true);
  3919. setNATFieldVal('conntype', r.connection_type, false);
  3920. // Advanced tab fields
  3921. setNATFieldVal('layer7', r.layer7_protocol, false);
  3922. setNATFieldVal('content', r.content, false);
  3923. setNATFieldVal('connbytes', r.connection_bytes, false);
  3924. setNATFieldVal('connrate', r.connection_rate, false);
  3925. setNATFieldVal('pcc', r.pcc, false);
  3926. setNATFieldVal('srcmac', r.src_mac_address, true);
  3927. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3928. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3929. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3930. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3931. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3932. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3933. setNATFieldVal('priority', r.priority, false);
  3934. setNATFieldVal('dscp', r.dscp, false);
  3935. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3936. if (r.tos) {
  3937. const tosEl = document.getElementById('nat-val-tos');
  3938. if (tosEl) tosEl.value = r.tos;
  3939. }
  3940. setNATFieldVal('pktsize', r.packet_size, false);
  3941. setNATFieldVal('random', r.random, false);
  3942. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3943. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3944. setNATFieldVal('ttl', r.ttl, false);
  3945. // Extra tab fields
  3946. setNATFieldVal('time', r.time, false);
  3947. if (r.days) {
  3948. toggleNATField('days', true);
  3949. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3950. const chk = document.getElementById(`nat-day-${d}`);
  3951. if (chk) chk.checked = r.days.includes(d);
  3952. });
  3953. } else {
  3954. toggleNATField('days', false);
  3955. }
  3956. setNATFieldVal('limit', r.limit, false);
  3957. setNATFieldVal('dstlimit', r.dst_limit, false);
  3958. setNATFieldVal('psd', r.psd, false);
  3959. // Action fields
  3960. if (r.jump_target) {
  3961. const jtEl = document.getElementById('nat-modal-jumptarget');
  3962. if (jtEl) jtEl.value = r.jump_target;
  3963. }
  3964. if (r.address_list) {
  3965. const alEl = document.getElementById('nat-modal-action-addrlist');
  3966. if (alEl) alEl.value = r.address_list;
  3967. }
  3968. if (r.address_list_timeout) {
  3969. const toEl = document.getElementById('nat-modal-action-timeout');
  3970. if (toEl) toEl.value = r.address_list_timeout;
  3971. }
  3972. setNATFieldVal('logprefix', r.log_prefix, false);
  3973. // Statistics
  3974. const bEl = document.getElementById('nat-stat-bytes');
  3975. const pEl = document.getElementById('nat-stat-packets');
  3976. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3977. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3978. state.natLastBytes = r.bytes || 0;
  3979. state.natLastPackets = r.packets || 0;
  3980. state.natLastTimestamp = Date.now();
  3981. state.natStatRateHistory = new Array(30).fill(0);
  3982. state.natStatPktHistory = new Array(30).fill(0);
  3983. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3984. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3985. toggleNATActionFields();
  3986. document.getElementById('nat-modal').classList.remove('hidden');
  3987. }
  3988. function closeNATModal() {
  3989. stopNATStatPolling();
  3990. document.getElementById('nat-modal').classList.add('hidden');
  3991. }
  3992. function copyNATRule() {
  3993. document.getElementById('nat-modal-id').value = '';
  3994. const badge = document.getElementById('nat-modal-badge');
  3995. if (badge) badge.innerText = 'New...';
  3996. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3997. }
  3998. function resetCurrentNATRuleCounters() {
  3999. state.natStatRateHistory = new Array(30).fill(0);
  4000. state.natStatPktHistory = new Array(30).fill(0);
  4001. state.natLastBytes = 0;
  4002. state.natLastPackets = 0;
  4003. state.natLastTimestamp = Date.now();
  4004. const bEl = document.getElementById('nat-stat-bytes');
  4005. const pEl = document.getElementById('nat-stat-packets');
  4006. const rEl = document.getElementById('nat-stat-rate');
  4007. const prEl = document.getElementById('nat-stat-pktrate');
  4008. if (bEl) bEl.value = '0 B';
  4009. if (pEl) pEl.value = '0';
  4010. if (rEl) rEl.value = '0 bps';
  4011. if (prEl) prEl.value = '0 p/s';
  4012. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4013. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4014. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4015. }
  4016. async function applyNATRule(closeAfter = false) {
  4017. const id = document.getElementById('nat-modal-id').value;
  4018. const chain = document.getElementById('nat-modal-chain').value;
  4019. const action = document.getElementById('nat-modal-action').value;
  4020. const comment = document.getElementById('nat-modal-comment').value.trim();
  4021. const enabled = document.getElementById('nat-modal-enabled').checked;
  4022. const src = getNATFieldVal('src', true);
  4023. const dst = getNATFieldVal('dst', true);
  4024. const srclist = getNATFieldVal('srclist', true);
  4025. const dstlist = getNATFieldVal('dstlist', true);
  4026. const srcgeo = getNATFieldVal('srcgeo', true);
  4027. const dstgeo = getNATFieldVal('dstgeo', true);
  4028. const proto = getNATFieldVal('proto', true);
  4029. const sport = getNATFieldVal('sport', true);
  4030. const dport = getNATFieldVal('dport', true);
  4031. const anyport = getNATFieldVal('anyport', true);
  4032. const iniface = getNATFieldVal('iniface', true);
  4033. const outiface = getNATFieldVal('outiface', true);
  4034. const inifacelist = getNATFieldVal('inifacelist', true);
  4035. const outifacelist = getNATFieldVal('outifacelist', true);
  4036. const pktmark = getNATFieldVal('pktmark', true);
  4037. const connmark = getNATFieldVal('connmark', true);
  4038. const routingmark = getNATFieldVal('routingmark', true);
  4039. const conntype = getNATFieldVal('conntype', false);
  4040. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4041. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4042. const payload = {
  4043. id,
  4044. chain,
  4045. action,
  4046. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4047. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4048. protocol: proto || 'all',
  4049. src_address: src,
  4050. dst_address: dst,
  4051. src_port: sport,
  4052. dst_port: dport,
  4053. any_port: anyport,
  4054. in_interface: iniface,
  4055. out_interface: outiface,
  4056. in_interface_list: inifacelist,
  4057. out_interface_list: outifacelist,
  4058. packet_mark: pktmark,
  4059. connection_mark: connmark,
  4060. routing_mark: routingmark,
  4061. connection_type: conntype,
  4062. src_address_list: srclist,
  4063. dst_address_list: dstlist,
  4064. src_geoip: srcgeo,
  4065. dst_geoip: dstgeo,
  4066. comment,
  4067. disabled: !enabled,
  4068. // Advanced tab
  4069. layer7_protocol: getNATFieldVal('layer7', false),
  4070. content: getNATFieldVal('content', false),
  4071. connection_bytes: getNATFieldVal('connbytes', false),
  4072. connection_rate: getNATFieldVal('connrate', false),
  4073. pcc: getNATFieldVal('pcc', false),
  4074. src_mac_address: getNATFieldVal('srcmac', true),
  4075. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4076. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4077. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4078. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4079. ipsec_policy: getNATFieldVal('ipsec', false),
  4080. ingress_priority: getNATFieldVal('ingresspriority', false),
  4081. priority: getNATFieldVal('priority', false),
  4082. dscp: getNATFieldVal('dscp', false),
  4083. tcp_mss: getNATFieldVal('tcpmss', false),
  4084. tos: document.getElementById('nat-val-tos')?.value || '',
  4085. packet_size: getNATFieldVal('pktsize', false),
  4086. random: getNATFieldVal('random', false),
  4087. icmp_options: getNATFieldVal('icmpoptions', false),
  4088. ipv4_options: getNATFieldVal('ipv4options', false),
  4089. ttl: getNATFieldVal('ttl', false),
  4090. // Extra tab
  4091. time: getNATFieldVal('time', false),
  4092. limit: getNATFieldVal('limit', false),
  4093. dst_limit: getNATFieldVal('dstlimit', false),
  4094. psd: getNATFieldVal('psd', false),
  4095. // Action tab
  4096. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4097. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4098. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4099. log: document.getElementById('nat-modal-log')?.checked || false,
  4100. log_prefix: getNATFieldVal('logprefix', false)
  4101. };
  4102. try {
  4103. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4104. method: 'POST',
  4105. headers: { 'Content-Type': 'application/json' },
  4106. body: JSON.stringify(payload)
  4107. });
  4108. if (res.ok) {
  4109. const data = await res.json();
  4110. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4111. loadFirewall(false);
  4112. if (closeAfter) {
  4113. closeNATModal();
  4114. } else {
  4115. if (data.id) {
  4116. document.getElementById('nat-modal-id').value = data.id;
  4117. const badge = document.getElementById('nat-modal-badge');
  4118. if (badge) badge.innerText = `#${data.id}`;
  4119. }
  4120. }
  4121. } else {
  4122. const err = await res.json();
  4123. showToast('Error', err.message || 'Failed to save rule', 'error');
  4124. }
  4125. } catch (err) {
  4126. showToast('Error', err.message, 'error');
  4127. }
  4128. }
  4129. function submitSaveNATRule(e) {
  4130. if (e && e.preventDefault) e.preventDefault();
  4131. return applyNATRule(true);
  4132. }
  4133. function startNATStatPolling() {
  4134. stopNATStatPolling();
  4135. pollNATRuleStats();
  4136. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4137. }
  4138. function stopNATStatPolling() {
  4139. if (state.natStatInterval) {
  4140. clearInterval(state.natStatInterval);
  4141. state.natStatInterval = null;
  4142. }
  4143. }
  4144. async function pollNATRuleStats() {
  4145. const id = document.getElementById('nat-modal-id')?.value;
  4146. if (!id) {
  4147. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4148. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4149. return;
  4150. }
  4151. try {
  4152. const res = await fetch(`${API_BASE}/firewall/nat`);
  4153. if (!res.ok) return;
  4154. const rules = await res.json();
  4155. const r = rules.find(x => x.id === id);
  4156. if (!r) return;
  4157. const now = Date.now();
  4158. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4159. state.natLastTimestamp = now;
  4160. const curBytes = r.bytes || 0;
  4161. const curPackets = r.packets || 0;
  4162. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4163. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4164. state.natLastBytes = curBytes;
  4165. state.natLastPackets = curPackets;
  4166. const rateBps = Math.round((deltaBytes * 8) / dt);
  4167. const ratePkt = Math.round(deltaPkts / dt);
  4168. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4169. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4170. state.natStatRateHistory.push(rateBps);
  4171. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4172. state.natStatPktHistory.push(ratePkt);
  4173. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4174. const bEl = document.getElementById('nat-stat-bytes');
  4175. const pEl = document.getElementById('nat-stat-packets');
  4176. const rEl = document.getElementById('nat-stat-rate');
  4177. const prEl = document.getElementById('nat-stat-pktrate');
  4178. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4179. if (pEl) pEl.value = curPackets.toLocaleString();
  4180. if (rEl) rEl.value = formatBps(rateBps);
  4181. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4182. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4183. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4184. } catch (e) {
  4185. console.error('Error polling NAT rule stats', e);
  4186. }
  4187. }
  4188. async function moveNATRule(id, dir) {
  4189. try {
  4190. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4191. method: 'POST',
  4192. headers: { 'Content-Type': 'application/json' },
  4193. body: JSON.stringify({ direction: dir })
  4194. });
  4195. if (res.ok) loadFirewall(false);
  4196. } catch (err) {
  4197. showToast('Error', err.message, 'error');
  4198. }
  4199. }
  4200. async function toggleNATRuleState(id, disabled) {
  4201. try {
  4202. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4203. method: 'POST',
  4204. headers: { 'Content-Type': 'application/json' },
  4205. body: JSON.stringify({ disabled })
  4206. });
  4207. if (res.ok) loadFirewall(false);
  4208. } catch (err) {
  4209. showToast('Error', err.message, 'error');
  4210. }
  4211. }
  4212. async function deleteNATRule(id) {
  4213. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4214. try {
  4215. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4216. if (res.ok) {
  4217. showToast('Deleted', 'NAT rule removed', 'success');
  4218. loadFirewall(false);
  4219. }
  4220. } catch (err) {
  4221. showToast('Error', err.message, 'error');
  4222. }
  4223. }
  4224. // ----------------- Mangle Rules -----------------
  4225. function renderMangleRules() {
  4226. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4227. const tbody = document.getElementById('mangle-table-body');
  4228. const empty = document.getElementById('mangle-empty');
  4229. if (!tbody) return;
  4230. tbody.innerHTML = '';
  4231. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4232. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4233. if (rules.length === 0) {
  4234. empty?.classList.remove('hidden');
  4235. return;
  4236. }
  4237. empty?.classList.add('hidden');
  4238. rules.forEach((r, idx) => {
  4239. const tr = document.createElement('tr');
  4240. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4241. let markVal = '<span class="text-slate-500">-</span>';
  4242. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4243. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4244. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4245. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4246. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4247. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4248. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4249. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4250. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4251. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4252. 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>`;
  4253. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4254. tr.innerHTML = `
  4255. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4256. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4257. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4258. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4259. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4260. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4261. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4262. <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>
  4263. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4264. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4265. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4266. </td>
  4267. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4268. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4269. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4270. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4271. <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>
  4272. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4273. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4274. </td>
  4275. `;
  4276. tbody.appendChild(tr);
  4277. });
  4278. }
  4279. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4280. function switchMangleRuleTab(tab) {
  4281. state.activeMangleRuleTab = tab;
  4282. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4283. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4284. btn.classList.add('text-slate-400', 'border-transparent');
  4285. });
  4286. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4287. if (activeBtn) {
  4288. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4289. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4290. }
  4291. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4292. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4293. if (activePane) activePane.classList.remove('hidden');
  4294. if (tab === 'statistics') {
  4295. startMangleStatPolling();
  4296. } else {
  4297. stopMangleStatPolling();
  4298. }
  4299. }
  4300. function toggleMangleField(fieldKey, expand) {
  4301. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4302. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4303. if (!plusBtn || !fieldBox) return;
  4304. if (expand) {
  4305. plusBtn.classList.add('hidden');
  4306. fieldBox.classList.remove('hidden');
  4307. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4308. if (valInput) valInput.focus();
  4309. } else {
  4310. fieldBox.classList.add('hidden');
  4311. plusBtn.classList.remove('hidden');
  4312. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4313. if (valInput) {
  4314. if (valInput.tagName === 'SELECT') {
  4315. valInput.selectedIndex = 0;
  4316. } else {
  4317. valInput.value = '';
  4318. }
  4319. }
  4320. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4321. if (invInput) invInput.checked = false;
  4322. if (fieldKey === 'cs') {
  4323. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4324. const el = document.getElementById(id);
  4325. if (el) el.checked = false;
  4326. });
  4327. }
  4328. if (fieldKey === 'natstate') {
  4329. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4330. const el = document.getElementById(id);
  4331. if (el) el.checked = false;
  4332. });
  4333. }
  4334. }
  4335. }
  4336. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4337. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4338. toggleMangleField(fieldKey, true);
  4339. let strVal = String(value);
  4340. if (hasInvert) {
  4341. const inv = strVal.startsWith('!');
  4342. if (inv) strVal = strVal.slice(1);
  4343. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4344. if (invEl) invEl.checked = inv;
  4345. }
  4346. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4347. if (valEl) valEl.value = strVal;
  4348. } else {
  4349. toggleMangleField(fieldKey, false);
  4350. }
  4351. }
  4352. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4353. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4354. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4355. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4356. let v = valEl ? valEl.value.trim() : '';
  4357. if (!v) return '';
  4358. if (hasInvert) {
  4359. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4360. if (invEl && invEl.checked) {
  4361. v = '!' + v.replace(/^!/, '');
  4362. }
  4363. }
  4364. return v;
  4365. }
  4366. function toggleMaximizeMangleModal() {
  4367. const win = document.getElementById('mangle-modal-window');
  4368. if (!win) return;
  4369. if (win.classList.contains('max-w-[720px]')) {
  4370. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4371. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4372. } else {
  4373. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4374. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4375. }
  4376. }
  4377. function toggleMangleActionFields() {
  4378. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4379. // Hide all dynamic rows first
  4380. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4381. const el = document.getElementById(`mangle-row-${id}`);
  4382. if (el) el.classList.add('hidden');
  4383. });
  4384. const jumpBox = document.getElementById('mangle-action-jump-box');
  4385. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4386. if (jumpBox) jumpBox.classList.add('hidden');
  4387. if (addrBox) addrBox.classList.add('hidden');
  4388. // Activate matching rows
  4389. if (act === 'mark-connection') {
  4390. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4391. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4392. } else if (act === 'mark-routing') {
  4393. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4394. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4395. } else if (act === 'mark-packet') {
  4396. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4397. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4398. } else if (act === 'change-mss') {
  4399. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4400. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4401. } else if (act === 'change-dscp') {
  4402. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4403. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4404. } else if (act === 'change-ttl') {
  4405. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4406. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4407. } else if (act === 'set-priority') {
  4408. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4409. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4410. } else if (act === 'route') {
  4411. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4412. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4413. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4414. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4415. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4416. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4417. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4418. } else if (act === 'jump') {
  4419. if (jumpBox) jumpBox.classList.remove('hidden');
  4420. } else if (act.includes('address-list') || act.includes('address list')) {
  4421. if (addrBox) addrBox.classList.remove('hidden');
  4422. }
  4423. if (act === 'log') {
  4424. const logEl = document.getElementById('mangle-modal-log');
  4425. if (logEl) logEl.checked = true;
  4426. toggleMangleField('logprefix', true);
  4427. }
  4428. }
  4429. function toggleMangleLogPrefix() {
  4430. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4431. toggleMangleField('logprefix', !!isLog);
  4432. }
  4433. const allMangleFieldKeys = [
  4434. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4435. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4436. 'routingmark', 'conntype', 'cs', 'natstate',
  4437. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4438. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4439. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4440. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4441. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4442. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4443. ];
  4444. function openAddMangleModal() {
  4445. switchMangleRuleTab('general');
  4446. const badge = document.getElementById('mangle-modal-badge');
  4447. if (badge) badge.innerText = 'New...';
  4448. document.getElementById('mangle-modal-id').value = '';
  4449. document.getElementById('mangle-modal-enabled').checked = true;
  4450. document.getElementById('mangle-modal-comment').value = '';
  4451. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4452. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4453. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4454. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4455. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4456. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4457. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4458. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4459. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4460. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4461. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4462. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4463. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4464. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4465. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4466. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4467. populateInterfaceSelect('mangle-val-iniface');
  4468. populateInterfaceSelect('mangle-val-outiface');
  4469. populateAddressListSelect('mangle-val-srclist');
  4470. populateAddressListSelect('mangle-val-dstlist');
  4471. populateGeoIPSelect('mangle-val-srcgeo');
  4472. populateGeoIPSelect('mangle-val-dstgeo');
  4473. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4474. resetCurrentMangleRuleCounters();
  4475. toggleMangleActionFields();
  4476. document.getElementById('mangle-modal').classList.remove('hidden');
  4477. }
  4478. function openEditMangleModal(id) {
  4479. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4480. if (!r) return;
  4481. switchMangleRuleTab('general');
  4482. const badge = document.getElementById('mangle-modal-badge');
  4483. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4484. document.getElementById('mangle-modal-id').value = r.id;
  4485. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4486. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4487. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4488. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4489. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4490. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4491. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4492. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4493. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4494. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4495. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4496. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4497. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4498. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4499. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4500. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4501. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4502. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4503. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4504. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4505. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4506. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4507. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4508. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4509. setMangleFieldVal('src', r.src_address, true);
  4510. setMangleFieldVal('dst', r.dst_address, true);
  4511. setMangleFieldVal('srclist', r.src_address_list, true);
  4512. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4513. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4514. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4515. if (r.protocol && r.protocol !== 'all') {
  4516. setMangleFieldVal('proto', r.protocol, true);
  4517. } else {
  4518. toggleMangleField('proto', false);
  4519. }
  4520. setMangleFieldVal('sport', r.src_port, true);
  4521. setMangleFieldVal('dport', r.dst_port, true);
  4522. setMangleFieldVal('anyport', r.any_port, true);
  4523. setMangleFieldVal('iniface', r.in_interface, true);
  4524. setMangleFieldVal('outiface', r.out_interface, true);
  4525. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4526. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4527. setMangleFieldVal('pktmark', r.packet_mark, true);
  4528. setMangleFieldVal('connmark', r.connection_mark, true);
  4529. setMangleFieldVal('routingmark', r.routing_mark, true);
  4530. setMangleFieldVal('conntype', r.connection_type, false);
  4531. // Connection State
  4532. const states = r.connection_state || [];
  4533. if (states.length > 0) {
  4534. toggleMangleField('cs', true);
  4535. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4536. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4537. if (el) el.checked = states.includes(s);
  4538. });
  4539. } else {
  4540. toggleMangleField('cs', false);
  4541. }
  4542. // Connection NAT State
  4543. const natStates = r.connection_nat_state || [];
  4544. if (natStates.length > 0) {
  4545. toggleMangleField('natstate', true);
  4546. ['srcnat', 'dstnat'].forEach(s => {
  4547. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4548. if (el) el.checked = natStates.includes(s);
  4549. });
  4550. } else {
  4551. toggleMangleField('natstate', false);
  4552. }
  4553. // Advanced tab fields
  4554. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4555. setMangleFieldVal('content', r.content, false);
  4556. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4557. setMangleFieldVal('connrate', r.connection_rate, false);
  4558. setMangleFieldVal('pcc', r.pcc, false);
  4559. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4560. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4561. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4562. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4563. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4564. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4565. setMangleFieldVal('tlshost', r.tls_host, false);
  4566. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4567. setMangleFieldVal('priority', r.priority, false);
  4568. setMangleFieldVal('dscp', r.dscp, false);
  4569. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4570. if (r.tos) {
  4571. const tosEl = document.getElementById('mangle-val-tos');
  4572. if (tosEl) tosEl.value = r.tos;
  4573. }
  4574. setMangleFieldVal('pktsize', r.packet_size, false);
  4575. setMangleFieldVal('random', r.random, false);
  4576. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4577. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4578. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4579. setMangleFieldVal('ttl', r.ttl, false);
  4580. // Extra tab fields
  4581. setMangleFieldVal('nth', r.nth, false);
  4582. setMangleFieldVal('connlimit', r.connection_limit, false);
  4583. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4584. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4585. setMangleFieldVal('hotspot', r.hotspot, false);
  4586. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4587. setMangleFieldVal('limit', r.limit, false);
  4588. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4589. setMangleFieldVal('time', r.time, false);
  4590. setMangleFieldVal('psd', r.psd, false);
  4591. // Action fields
  4592. if (r.jump_target) {
  4593. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4594. if (jtEl) jtEl.value = r.jump_target;
  4595. }
  4596. if (r.address_list) {
  4597. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4598. if (alEl) alEl.value = r.address_list;
  4599. }
  4600. if (r.address_list_timeout) {
  4601. const toEl = document.getElementById('mangle-modal-action-timeout');
  4602. if (toEl) toEl.value = r.address_list_timeout;
  4603. }
  4604. setMangleFieldVal('logprefix', r.log_prefix, false);
  4605. // Statistics
  4606. const bEl = document.getElementById('mangle-stat-bytes');
  4607. const pEl = document.getElementById('mangle-stat-packets');
  4608. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4609. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4610. state.mangleLastBytes = r.bytes || 0;
  4611. state.mangleLastPackets = r.packets || 0;
  4612. state.mangleLastTimestamp = Date.now();
  4613. state.mangleStatRateHistory = new Array(30).fill(0);
  4614. state.mangleStatPktHistory = new Array(30).fill(0);
  4615. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4616. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4617. toggleMangleActionFields();
  4618. document.getElementById('mangle-modal').classList.remove('hidden');
  4619. }
  4620. function closeMangleModal() {
  4621. stopMangleStatPolling();
  4622. document.getElementById('mangle-modal').classList.add('hidden');
  4623. }
  4624. function copyMangleRule() {
  4625. document.getElementById('mangle-modal-id').value = '';
  4626. const badge = document.getElementById('mangle-modal-badge');
  4627. if (badge) badge.innerText = 'New...';
  4628. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4629. }
  4630. function resetCurrentMangleRuleCounters() {
  4631. state.mangleStatRateHistory = new Array(30).fill(0);
  4632. state.mangleStatPktHistory = new Array(30).fill(0);
  4633. state.mangleLastBytes = 0;
  4634. state.mangleLastPackets = 0;
  4635. state.mangleLastTimestamp = Date.now();
  4636. const bEl = document.getElementById('mangle-stat-bytes');
  4637. const pEl = document.getElementById('mangle-stat-packets');
  4638. const rEl = document.getElementById('mangle-stat-rate');
  4639. const prEl = document.getElementById('mangle-stat-pktrate');
  4640. if (bEl) bEl.value = '0 B';
  4641. if (pEl) pEl.value = '0';
  4642. if (rEl) rEl.value = '0 bps';
  4643. if (prEl) prEl.value = '0 p/s';
  4644. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4645. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4646. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4647. }
  4648. async function applyMangleRule(closeAfter = false) {
  4649. const id = document.getElementById('mangle-modal-id').value;
  4650. const chain = document.getElementById('mangle-modal-chain').value;
  4651. const action = document.getElementById('mangle-modal-action').value;
  4652. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4653. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4654. const src = getMangleFieldVal('src', true);
  4655. const dst = getMangleFieldVal('dst', true);
  4656. const srclist = getMangleFieldVal('srclist', true);
  4657. const dstlist = getMangleFieldVal('dstlist', true);
  4658. const srcgeo = getMangleFieldVal('srcgeo', true);
  4659. const dstgeo = getMangleFieldVal('dstgeo', true);
  4660. const proto = getMangleFieldVal('proto', true);
  4661. const sport = getMangleFieldVal('sport', true);
  4662. const dport = getMangleFieldVal('dport', true);
  4663. const anyport = getMangleFieldVal('anyport', true);
  4664. const iniface = getMangleFieldVal('iniface', true);
  4665. const outiface = getMangleFieldVal('outiface', true);
  4666. const inifacelist = getMangleFieldVal('inifacelist', true);
  4667. const outifacelist = getMangleFieldVal('outifacelist', true);
  4668. const pktmark = getMangleFieldVal('pktmark', true);
  4669. const connmark = getMangleFieldVal('connmark', true);
  4670. const routingmark = getMangleFieldVal('routingmark', true);
  4671. const conntype = getMangleFieldVal('conntype', false);
  4672. const states = [];
  4673. const csBox = document.getElementById('mangle-field-cs');
  4674. if (csBox && !csBox.classList.contains('hidden')) {
  4675. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4676. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4677. });
  4678. }
  4679. const natStates = [];
  4680. const natBox = document.getElementById('mangle-field-natstate');
  4681. if (natBox && !natBox.classList.contains('hidden')) {
  4682. ['srcnat', 'dstnat'].forEach(s => {
  4683. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4684. });
  4685. }
  4686. const payload = {
  4687. id,
  4688. chain,
  4689. action,
  4690. protocol: proto || 'all',
  4691. src_address: src,
  4692. dst_address: dst,
  4693. src_port: sport,
  4694. dst_port: dport,
  4695. any_port: anyport,
  4696. in_interface: iniface,
  4697. out_interface: outiface,
  4698. in_interface_list: inifacelist,
  4699. out_interface_list: outifacelist,
  4700. packet_mark: pktmark,
  4701. connection_mark: connmark,
  4702. routing_mark: routingmark,
  4703. connection_type: conntype,
  4704. connection_state: states,
  4705. connection_nat_state: natStates,
  4706. src_address_list: srclist,
  4707. dst_address_list: dstlist,
  4708. src_geoip: srcgeo,
  4709. dst_geoip: dstgeo,
  4710. comment,
  4711. disabled: !enabled,
  4712. // Advanced tab
  4713. layer7_protocol: getMangleFieldVal('layer7', false),
  4714. content: getMangleFieldVal('content', false),
  4715. connection_bytes: getMangleFieldVal('connbytes', false),
  4716. connection_rate: getMangleFieldVal('connrate', false),
  4717. pcc: getMangleFieldVal('pcc', false),
  4718. src_mac_address: getMangleFieldVal('srcmac', true),
  4719. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4720. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4721. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4722. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4723. ipsec_policy: getMangleFieldVal('ipsec', false),
  4724. tls_host: getMangleFieldVal('tlshost', false),
  4725. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4726. priority: getMangleFieldVal('priority', false),
  4727. dscp: getMangleFieldVal('dscp', false),
  4728. tcp_mss: getMangleFieldVal('tcpmss', false),
  4729. tos: document.getElementById('mangle-val-tos')?.value || '',
  4730. packet_size: getMangleFieldVal('pktsize', false),
  4731. random: getMangleFieldVal('random', false),
  4732. tcp_flags: getMangleFieldVal('tcpflags', false),
  4733. icmp_options: getMangleFieldVal('icmpoptions', false),
  4734. ipv4_options: getMangleFieldVal('ipv4options', false),
  4735. ttl: getMangleFieldVal('ttl', false),
  4736. // Extra tab
  4737. nth: getMangleFieldVal('nth', false),
  4738. connection_limit: getMangleFieldVal('connlimit', false),
  4739. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4740. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4741. hotspot: getMangleFieldVal('hotspot', false),
  4742. ip_fragment: getMangleFieldVal('ipfragment', false),
  4743. limit: getMangleFieldVal('limit', false),
  4744. dst_limit: getMangleFieldVal('dstlimit', false),
  4745. time: getMangleFieldVal('time', false),
  4746. psd: getMangleFieldVal('psd', false),
  4747. // Action tab
  4748. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4749. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4750. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4751. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4752. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4753. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4754. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4755. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4756. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4757. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4758. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4759. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4760. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4761. log: document.getElementById('mangle-modal-log')?.checked || false,
  4762. log_prefix: getMangleFieldVal('logprefix', false)
  4763. };
  4764. try {
  4765. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4766. method: 'POST',
  4767. headers: { 'Content-Type': 'application/json' },
  4768. body: JSON.stringify(payload)
  4769. });
  4770. if (res.ok) {
  4771. const data = await res.json();
  4772. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4773. loadFirewall(false);
  4774. if (closeAfter) {
  4775. closeMangleModal();
  4776. } else {
  4777. if (data.id) {
  4778. document.getElementById('mangle-modal-id').value = data.id;
  4779. const badge = document.getElementById('mangle-modal-badge');
  4780. if (badge) badge.innerText = `#${data.id}`;
  4781. }
  4782. }
  4783. } else {
  4784. const err = await res.json();
  4785. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4786. }
  4787. } catch (err) {
  4788. showToast('Error', err.message, 'error');
  4789. }
  4790. }
  4791. function submitSaveMangleRule(e) {
  4792. if (e && e.preventDefault) e.preventDefault();
  4793. return applyMangleRule(true);
  4794. }
  4795. function startMangleStatPolling() {
  4796. stopMangleStatPolling();
  4797. pollMangleRuleStats();
  4798. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4799. }
  4800. function stopMangleStatPolling() {
  4801. if (state.mangleStatInterval) {
  4802. clearInterval(state.mangleStatInterval);
  4803. state.mangleStatInterval = null;
  4804. }
  4805. }
  4806. async function pollMangleRuleStats() {
  4807. const id = document.getElementById('mangle-modal-id')?.value;
  4808. if (!id) {
  4809. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4810. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4811. return;
  4812. }
  4813. try {
  4814. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4815. if (!res.ok) return;
  4816. const rules = await res.json();
  4817. const r = rules.find(x => x.id === id);
  4818. if (!r) return;
  4819. const now = Date.now();
  4820. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4821. state.mangleLastTimestamp = now;
  4822. const curBytes = r.bytes || 0;
  4823. const curPackets = r.packets || 0;
  4824. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4825. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4826. state.mangleLastBytes = curBytes;
  4827. state.mangleLastPackets = curPackets;
  4828. const rateBps = Math.round((deltaBytes * 8) / dt);
  4829. const ratePkt = Math.round(deltaPkts / dt);
  4830. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4831. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4832. state.mangleStatRateHistory.push(rateBps);
  4833. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4834. state.mangleStatPktHistory.push(ratePkt);
  4835. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4836. const bEl = document.getElementById('mangle-stat-bytes');
  4837. const pEl = document.getElementById('mangle-stat-packets');
  4838. const rEl = document.getElementById('mangle-stat-rate');
  4839. const prEl = document.getElementById('mangle-stat-pktrate');
  4840. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4841. if (pEl) pEl.value = curPackets.toLocaleString();
  4842. if (rEl) rEl.value = formatBps(rateBps);
  4843. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4844. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4845. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4846. } catch (e) {
  4847. console.error('Error polling Mangle rule stats', e);
  4848. }
  4849. }
  4850. async function moveMangleRule(id, dir) {
  4851. try {
  4852. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4853. method: 'POST',
  4854. headers: { 'Content-Type': 'application/json' },
  4855. body: JSON.stringify({ direction: dir })
  4856. });
  4857. if (res.ok) loadFirewall(false);
  4858. } catch (err) {
  4859. showToast('Error', err.message, 'error');
  4860. }
  4861. }
  4862. async function toggleMangleRuleState(id, disabled) {
  4863. try {
  4864. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4865. method: 'POST',
  4866. headers: { 'Content-Type': 'application/json' },
  4867. body: JSON.stringify({ disabled })
  4868. });
  4869. if (res.ok) loadFirewall(false);
  4870. } catch (err) {
  4871. showToast('Error', err.message, 'error');
  4872. }
  4873. }
  4874. async function deleteMangleRule(id) {
  4875. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4876. try {
  4877. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4878. if (res.ok) {
  4879. showToast('Deleted', 'Mangle rule removed', 'success');
  4880. loadFirewall(false);
  4881. }
  4882. } catch (err) {
  4883. showToast('Error', err.message, 'error');
  4884. }
  4885. }
  4886. // ----------------- Address Lists -----------------
  4887. function renderAddressLists() {
  4888. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4889. const tbody = document.getElementById('addrlist-table-body');
  4890. const empty = document.getElementById('addrlist-empty');
  4891. if (!tbody) return;
  4892. tbody.innerHTML = '';
  4893. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4894. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4895. // Update filter select
  4896. const sel = document.getElementById('addrlist-filter-name');
  4897. if (sel) {
  4898. const cur = sel.value;
  4899. sel.innerHTML = '<option value="">All Lists</option>';
  4900. const set = new Set((state.addressLists || []).map(a => a.name));
  4901. set.forEach(n => {
  4902. const opt = document.createElement('option');
  4903. opt.value = n;
  4904. opt.innerText = n;
  4905. if (n === cur) opt.selected = true;
  4906. sel.appendChild(opt);
  4907. });
  4908. }
  4909. if (entries.length === 0) {
  4910. empty?.classList.remove('hidden');
  4911. return;
  4912. }
  4913. empty?.classList.add('hidden');
  4914. entries.forEach((e, idx) => {
  4915. const tr = document.createElement('tr');
  4916. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4917. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4918. tr.innerHTML = `
  4919. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4920. <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>
  4921. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4922. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4923. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4924. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4925. <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>
  4926. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4927. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4928. </td>
  4929. `;
  4930. tbody.appendChild(tr);
  4931. });
  4932. populateCommonAddrListDatalist();
  4933. }
  4934. function openAddAddrListModal() {
  4935. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4936. document.getElementById('addrlist-modal-id').value = '';
  4937. document.getElementById('addrlist-modal-name').value = '';
  4938. document.getElementById('addrlist-modal-addr').value = '';
  4939. document.getElementById('addrlist-modal-comment').value = '';
  4940. document.getElementById('addrlist-modal-disabled').checked = false;
  4941. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4942. if (submitBtn) submitBtn.innerText = 'Add to List';
  4943. document.getElementById('addrlist-modal').classList.remove('hidden');
  4944. }
  4945. function openEditAddrListModal(id) {
  4946. const e = (state.addressLists || []).find(item => item.id === id);
  4947. if (!e) return;
  4948. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4949. document.getElementById('addrlist-modal-id').value = e.id;
  4950. document.getElementById('addrlist-modal-name').value = e.name;
  4951. document.getElementById('addrlist-modal-addr').value = e.address;
  4952. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4953. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4954. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4955. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4956. document.getElementById('addrlist-modal').classList.remove('hidden');
  4957. }
  4958. function closeAddrListModal() {
  4959. document.getElementById('addrlist-modal').classList.add('hidden');
  4960. }
  4961. async function submitSaveAddrList(e) {
  4962. e.preventDefault();
  4963. const id = document.getElementById('addrlist-modal-id').value;
  4964. const name = document.getElementById('addrlist-modal-name').value.trim();
  4965. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4966. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4967. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4968. try {
  4969. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4970. method: 'POST',
  4971. headers: { 'Content-Type': 'application/json' },
  4972. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4973. });
  4974. if (res.ok) {
  4975. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4976. closeAddrListModal();
  4977. loadFirewall(false);
  4978. } else {
  4979. const err = await res.json();
  4980. showToast('Error', err.message || 'Failed to save address list', 'error');
  4981. }
  4982. } catch (err) {
  4983. showToast('Error', err.message, 'error');
  4984. }
  4985. }
  4986. async function toggleAddrListState(id, disabled) {
  4987. try {
  4988. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4989. method: 'POST',
  4990. headers: { 'Content-Type': 'application/json' },
  4991. body: JSON.stringify({ disabled })
  4992. });
  4993. if (res.ok) {
  4994. loadFirewall(false);
  4995. }
  4996. } catch (err) {
  4997. showToast('Error', err.message, 'error');
  4998. }
  4999. }
  5000. async function deleteAddrList(id) {
  5001. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5002. try {
  5003. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5004. if (res.ok) {
  5005. showToast('Deleted', 'Address list item removed', 'info');
  5006. loadFirewall(false);
  5007. }
  5008. } catch (err) {
  5009. showToast('Error', err.message, 'error');
  5010. }
  5011. }
  5012. // ----------------- Geo-Location IP Management -----------------
  5013. async function loadGeoIP() {
  5014. try {
  5015. const [statusRes, countriesRes] = await Promise.all([
  5016. fetch(`${API_BASE}/firewall/geoip/status`),
  5017. fetch(`${API_BASE}/firewall/geoip/countries`)
  5018. ]);
  5019. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5020. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5021. updateGeoHeader();
  5022. renderGeoCountries();
  5023. } catch (err) {
  5024. console.error('Failed to load GeoIP:', err);
  5025. }
  5026. }
  5027. function getGeoUsageMap() {
  5028. const usage = {};
  5029. const checkRule = (r, type) => {
  5030. ['src_geoip', 'dst_geoip'].forEach(field => {
  5031. let val = (r && r[field]) || '';
  5032. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5033. if (code) {
  5034. if (!usage[code]) usage[code] = [];
  5035. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5036. if (!usage[code].includes(label)) usage[code].push(label);
  5037. }
  5038. });
  5039. };
  5040. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5041. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5042. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5043. return usage;
  5044. }
  5045. function updateGeoHeader() {
  5046. const s = state.geoStatus || {};
  5047. const statusBadge = document.getElementById('geo-status-badge');
  5048. if (statusBadge) {
  5049. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5050. statusBadge.className = s.auto_update
  5051. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5052. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5053. }
  5054. const intervalLabel = document.getElementById('geo-interval-label');
  5055. if (intervalLabel) {
  5056. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5057. }
  5058. const usageMap = getGeoUsageMap();
  5059. const inUseCount = Object.keys(usageMap).length;
  5060. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5061. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5062. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5063. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5064. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5065. if (lastSyncEl) {
  5066. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5067. const d = new Date(s.last_updated);
  5068. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5069. } else {
  5070. lastSyncEl.innerText = 'Never (Sync Pending)';
  5071. }
  5072. }
  5073. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5074. if (nextSyncEl) {
  5075. if (s.next_update && !s.next_update.startsWith('0001')) {
  5076. const d = new Date(s.next_update);
  5077. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5078. } else {
  5079. nextSyncEl.innerText = '-';
  5080. }
  5081. }
  5082. const badge = document.getElementById('fw-badge-geo');
  5083. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5084. }
  5085. function renderGeoCountries() {
  5086. const tbody = document.getElementById('geo-table-body');
  5087. const empty = document.getElementById('geo-empty');
  5088. if (!tbody) return;
  5089. tbody.innerHTML = '';
  5090. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5091. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5092. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5093. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5094. const usageMap = getGeoUsageMap();
  5095. const countries = (state.geoCountries || []).filter(c => {
  5096. const isUsed = !!usageMap[c.code];
  5097. if (inUseOnly && !isUsed) return false;
  5098. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5099. if (continent && c.continent !== continent) return false;
  5100. if (q) {
  5101. const matchCode = c.code.toLowerCase().includes(q);
  5102. const matchName = c.name.toLowerCase().includes(q);
  5103. if (!matchCode && !matchName) return false;
  5104. }
  5105. return true;
  5106. });
  5107. if (countries.length === 0) {
  5108. empty?.classList.remove('hidden');
  5109. return;
  5110. }
  5111. empty?.classList.add('hidden');
  5112. countries.forEach(c => {
  5113. const tr = document.createElement('tr');
  5114. const isUsed = !!usageMap[c.code];
  5115. const rulesUsing = usageMap[c.code] || [];
  5116. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5117. let statusHtml = '';
  5118. if (isUsed) {
  5119. 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>`;
  5120. } else if (c.subnet_count > 0) {
  5121. 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>';
  5122. } else {
  5123. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5124. }
  5125. tr.innerHTML = `
  5126. <td class="py-2.5 px-3 text-center">
  5127. <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'}">
  5128. ${c.code}
  5129. </span>
  5130. </td>
  5131. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5132. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5133. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5134. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5135. </td>
  5136. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5137. <td class="py-2.5 px-3">
  5138. ${statusHtml}
  5139. </td>
  5140. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5141. <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>
  5142. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5143. </td>
  5144. `;
  5145. tbody.appendChild(tr);
  5146. });
  5147. }
  5148. function quickFilterGeo(preset) {
  5149. const searchInput = document.getElementById('geo-search-input');
  5150. const continentSel = document.getElementById('geo-continent-filter');
  5151. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5152. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5153. if (searchInput) searchInput.value = '';
  5154. if (continentSel) continentSel.value = '';
  5155. if (inUseCheck) inUseCheck.checked = false;
  5156. if (cachedCheck) cachedCheck.checked = false;
  5157. if (preset === 'GR') {
  5158. if (searchInput) searchInput.value = 'Greece';
  5159. } else if (preset === 'Europe') {
  5160. if (continentSel) continentSel.value = 'Europe';
  5161. } else if (preset === 'HIGHRISK') {
  5162. if (searchInput) searchInput.value = 'China';
  5163. }
  5164. renderGeoCountries();
  5165. }
  5166. async function toggleGeoCountry(code, enabled) {
  5167. try {
  5168. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5169. method: 'POST',
  5170. headers: { 'Content-Type': 'application/json' },
  5171. body: JSON.stringify({ enabled })
  5172. });
  5173. if (res.ok) {
  5174. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5175. loadGeoIP();
  5176. } else {
  5177. const err = await res.json();
  5178. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5179. }
  5180. } catch (err) {
  5181. showToast('Error', err.message, 'error');
  5182. }
  5183. }
  5184. async function updateGeoCountry(code) {
  5185. try {
  5186. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5187. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5188. if (res.ok) {
  5189. const data = await res.json();
  5190. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5191. loadGeoIP();
  5192. } else {
  5193. const err = await res.json();
  5194. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5195. }
  5196. } catch (err) {
  5197. showToast('Error', err.message, 'error');
  5198. }
  5199. }
  5200. async function triggerGeoUpdateNow() {
  5201. const spinner = document.getElementById('geo-update-spinner');
  5202. if (spinner) spinner.classList.remove('hidden');
  5203. try {
  5204. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5205. if (res.ok) {
  5206. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5207. setTimeout(() => {
  5208. loadGeoIP();
  5209. if (spinner) spinner.classList.add('hidden');
  5210. }, 2500);
  5211. } else {
  5212. const err = await res.json();
  5213. showToast('Notice', err.message || 'Update in progress', 'info');
  5214. if (spinner) spinner.classList.add('hidden');
  5215. }
  5216. } catch (err) {
  5217. showToast('Error', err.message, 'error');
  5218. if (spinner) spinner.classList.add('hidden');
  5219. }
  5220. }
  5221. async function applyGeoPreset(preset) {
  5222. try {
  5223. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5224. method: 'POST',
  5225. headers: { 'Content-Type': 'application/json' },
  5226. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5227. });
  5228. if (res.ok) {
  5229. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5230. loadGeoIP();
  5231. }
  5232. } catch (err) {
  5233. showToast('Error', err.message, 'error');
  5234. }
  5235. }
  5236. function openGeoIntervalModal() {
  5237. const s = state.geoStatus || {};
  5238. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5239. const sel = document.getElementById('geo-cfg-interval');
  5240. const customBox = document.getElementById('geo-cfg-custom-box');
  5241. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5242. const curHours = s.interval_hours || 24;
  5243. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5244. if (matchOption) {
  5245. sel.value = String(curHours);
  5246. customBox.classList.add('hidden');
  5247. } else {
  5248. sel.value = 'custom';
  5249. customHoursInput.value = curHours;
  5250. customBox.classList.remove('hidden');
  5251. }
  5252. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5253. }
  5254. function closeGeoIntervalModal() {
  5255. document.getElementById('geo-interval-modal').classList.add('hidden');
  5256. }
  5257. function toggleCustomGeoInterval() {
  5258. const val = document.getElementById('geo-cfg-interval').value;
  5259. const customBox = document.getElementById('geo-cfg-custom-box');
  5260. if (val === 'custom') {
  5261. customBox.classList.remove('hidden');
  5262. } else {
  5263. customBox.classList.add('hidden');
  5264. }
  5265. }
  5266. async function submitGeoIntervalSettings(e) {
  5267. e.preventDefault();
  5268. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5269. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5270. let hours = 24;
  5271. if (intervalVal === 'custom') {
  5272. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5273. } else {
  5274. hours = parseInt(intervalVal, 10) || 24;
  5275. }
  5276. try {
  5277. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5278. method: 'POST',
  5279. headers: { 'Content-Type': 'application/json' },
  5280. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5281. });
  5282. if (res.ok) {
  5283. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5284. closeGeoIntervalModal();
  5285. loadGeoIP();
  5286. } else {
  5287. const err = await res.json();
  5288. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5289. }
  5290. } catch (err) {
  5291. showToast('Error', err.message, 'error');
  5292. }
  5293. }
  5294. async function viewGeoSubnets(code, name) {
  5295. if (!name) {
  5296. const found = (state.geoCountries || []).find(x => x.code === code);
  5297. name = found ? found.name : code;
  5298. }
  5299. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5300. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5301. const listEl = document.getElementById('geo-subnets-list');
  5302. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5303. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5304. try {
  5305. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5306. if (res.ok) {
  5307. const data = await res.json();
  5308. const subnets = data.subnets || [];
  5309. if (subnets.length === 0) {
  5310. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5311. } else {
  5312. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5313. }
  5314. } else {
  5315. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5316. }
  5317. } catch (err) {
  5318. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5319. }
  5320. }
  5321. function closeGeoSubnetsModal() {
  5322. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5323. }
  5324. // ----------------- Active Connections Tracking -----------------
  5325. async function loadConnections() {
  5326. try {
  5327. const res = await fetch(`${API_BASE}/firewall/connections`);
  5328. const data = await res.json();
  5329. state.connections = Array.isArray(data) ? data : [];
  5330. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5331. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5332. renderConnections();
  5333. } catch (err) {
  5334. console.error('Failed to load connections:', err);
  5335. }
  5336. }
  5337. function renderConnections() {
  5338. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5339. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5340. const tbody = document.getElementById('conns-table-body');
  5341. const empty = document.getElementById('conns-empty');
  5342. if (!tbody) return;
  5343. tbody.innerHTML = '';
  5344. const conns = (state.connections || []).filter(c => {
  5345. if (protoFilter && c.protocol !== protoFilter) return false;
  5346. if (search) {
  5347. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5348. if (!line.includes(search)) return false;
  5349. }
  5350. return true;
  5351. });
  5352. if (conns.length === 0) {
  5353. empty?.classList.remove('hidden');
  5354. return;
  5355. }
  5356. empty?.classList.add('hidden');
  5357. conns.slice(0, 150).forEach(c => {
  5358. const tr = document.createElement('tr');
  5359. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5360. let stateColor = 'text-slate-400';
  5361. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5362. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5363. tr.innerHTML = `
  5364. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5365. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5366. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5367. <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>
  5368. <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>
  5369. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5370. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5371. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5372. <td class="py-2.5 px-3 text-right font-sans">
  5373. <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>
  5374. </td>
  5375. `;
  5376. tbody.appendChild(tr);
  5377. });
  5378. }
  5379. async function killConnection(protocol, src, sport, dst, dport) {
  5380. try {
  5381. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5382. method: 'POST',
  5383. headers: { 'Content-Type': 'application/json' },
  5384. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5385. });
  5386. if (res.ok) {
  5387. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5388. loadConnections();
  5389. }
  5390. } catch (err) {
  5391. showToast('Error', err.message, 'error');
  5392. }
  5393. }
  5394. async function resetFirewallCounters() {
  5395. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5396. try {
  5397. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5398. if (res.ok) {
  5399. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5400. loadFirewall(false);
  5401. }
  5402. } catch (err) {
  5403. showToast('Error', err.message, 'error');
  5404. }
  5405. }
  5406. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5407. function switchRoutesSubTab(tab) {
  5408. state.routesSubTab = tab;
  5409. const tabs = ['routes', 'rules', 'tables'];
  5410. tabs.forEach(t => {
  5411. const panel = document.getElementById(`routes-subtab-${t}`);
  5412. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5413. if (panel) {
  5414. if (t === tab) panel.classList.remove('hidden');
  5415. else panel.classList.add('hidden');
  5416. }
  5417. if (btn) {
  5418. if (t === tab) {
  5419. 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';
  5420. } else {
  5421. 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';
  5422. }
  5423. }
  5424. });
  5425. setTimeout(initTableSorting, 50);
  5426. }
  5427. async function loadRoutes() {
  5428. try {
  5429. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5430. fetch(`${API_BASE}/routes`),
  5431. fetch(`${API_BASE}/routing/rules`),
  5432. fetch(`${API_BASE}/routing/tables`)
  5433. ]);
  5434. if (routesRes.ok) state.routes = await routesRes.json();
  5435. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5436. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5437. const bRoutes = document.getElementById('routes-badge-routes');
  5438. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5439. const showSystem = document.getElementById('prule-show-system')?.checked;
  5440. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5441. const bRules = document.getElementById('routes-badge-rules');
  5442. if (bRules) bRules.innerText = userRules.length;
  5443. const bTables = document.getElementById('routes-badge-tables');
  5444. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5445. const bRoutesCount = document.getElementById('badge-routes-count');
  5446. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5447. renderRoutesList();
  5448. renderPolicyRules();
  5449. renderRoutingTables();
  5450. } catch (err) {
  5451. console.error('Failed to load routing:', err);
  5452. }
  5453. }
  5454. function renderRoutesList() {
  5455. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5456. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5457. const tbody = document.getElementById('routes-table-body');
  5458. const empty = document.getElementById('routes-empty');
  5459. if (!tbody) return;
  5460. tbody.innerHTML = '';
  5461. // Update table filter select
  5462. const sel = document.getElementById('routes-filter-table');
  5463. if (sel) {
  5464. const cur = sel.value;
  5465. sel.innerHTML = '<option value="">All Tables</option>';
  5466. (state.routingTables || []).forEach(t => {
  5467. const opt = document.createElement('option');
  5468. opt.value = t.name;
  5469. opt.innerText = t.name;
  5470. if (t.name === cur) opt.selected = true;
  5471. sel.appendChild(opt);
  5472. });
  5473. }
  5474. const routes = (state.routes || []).filter(r => {
  5475. if (tableFilter && r.routing_table !== tableFilter) return false;
  5476. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5477. if (typeFilter === 'multicast' && !r.multicast) return false;
  5478. if (typeFilter === 'static' && !r.static) return false;
  5479. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5480. if (typeFilter === 'connected' && !r.connect) return false;
  5481. return true;
  5482. });
  5483. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5484. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5485. let summaryText = `${routes.length} Routes`;
  5486. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5487. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5488. const badgeEl = document.getElementById('routes-count-badge');
  5489. if (badgeEl) badgeEl.innerText = summaryText;
  5490. if (routes.length === 0) {
  5491. empty?.classList.remove('hidden');
  5492. return;
  5493. }
  5494. empty?.classList.add('hidden');
  5495. routes.forEach(r => {
  5496. const tr = document.createElement('tr');
  5497. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5498. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5499. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5500. let flags = '';
  5501. if (r.dynamic) flags += 'D';
  5502. if (r.active) flags += 'A';
  5503. if (r.connect) flags += 'C';
  5504. if (r.static) flags += 'S';
  5505. if (r.ecmp) flags += 'E';
  5506. if (r.multicast) flags += 'M';
  5507. if (r.disabled) flags += 'X';
  5508. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5509. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5510. if (r.check_gateway === 'internet') {
  5511. if (r.health_status === 'online') {
  5512. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5513. healthCell = `
  5514. <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)">
  5515. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5516. <span>Internet OK (${ms}ms)</span>
  5517. </span>
  5518. `;
  5519. } else if (r.health_status === 'offline') {
  5520. healthCell = `
  5521. <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.">
  5522. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5523. <span>Internet Down</span>
  5524. </span>
  5525. `;
  5526. } else {
  5527. healthCell = `
  5528. <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">
  5529. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  5530. <span>Checking...</span>
  5531. </span>
  5532. `;
  5533. }
  5534. } else if (r.check_gateway === 'ping') {
  5535. if (r.health_status === 'online') {
  5536. healthCell = `
  5537. <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">
  5538. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  5539. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  5540. </span>
  5541. `;
  5542. } else if (r.health_status === 'offline') {
  5543. healthCell = `
  5544. <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">
  5545. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5546. <span>Gateway Dead</span>
  5547. </span>
  5548. `;
  5549. }
  5550. }
  5551. const flagDescriptions = [];
  5552. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  5553. if (r.active) flagDescriptions.push('Active (A)');
  5554. if (r.connect) flagDescriptions.push('Connected (C)');
  5555. if (r.static) flagDescriptions.push('Static (S)');
  5556. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  5557. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  5558. if (r.disabled) flagDescriptions.push('Disabled (X)');
  5559. tr.innerHTML = `
  5560. <td class="py-2.5 px-3 text-center">
  5561. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  5562. 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')
  5563. }" title="Flags: ${flagDescriptions.join(', ')}">
  5564. ${flags || '-'}
  5565. </span>
  5566. </td>
  5567. <td class="py-2.5 px-3">
  5568. <div class="flex items-center gap-1.5 flex-wrap">
  5569. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  5570. ${r.ecmp ? `
  5571. <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)">
  5572. <span>⚡ ECMP</span>
  5573. </span>
  5574. ` : ''}
  5575. ${r.multicast ? `
  5576. <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">
  5577. <span>IGMP</span>
  5578. </span>
  5579. ` : ''}
  5580. </div>
  5581. </td>
  5582. <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>
  5583. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5584. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5585. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5586. <td class="py-2.5 px-3">${healthCell}</td>
  5587. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5588. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5589. ${r.static ? `
  5590. <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>
  5591. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5592. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5593. ` : `
  5594. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5595. `}
  5596. </td>
  5597. `;
  5598. tbody.appendChild(tr);
  5599. });
  5600. }
  5601. function openAddRouteModal() {
  5602. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5603. document.getElementById('route-modal-id').value = '';
  5604. document.getElementById('route-modal-old-dst').value = '';
  5605. document.getElementById('route-modal-old-gw').value = '';
  5606. document.getElementById('route-modal-old-distance').value = '';
  5607. document.getElementById('route-modal-old-table').value = '';
  5608. document.getElementById('route-modal-old-iface').value = '';
  5609. const dstInput = document.getElementById('route-modal-dst');
  5610. const gwInput = document.getElementById('route-modal-gw');
  5611. const distInput = document.getElementById('route-modal-distance');
  5612. const ifaceSelect = document.getElementById('route-modal-iface');
  5613. const tableSelect = document.getElementById('route-modal-table');
  5614. const commentInput = document.getElementById('route-modal-comment');
  5615. const disCheck = document.getElementById('route-modal-disabled');
  5616. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5617. dstInput.disabled = false;
  5618. dstInput.value = '0.0.0.0/0';
  5619. gwInput.disabled = false;
  5620. gwInput.value = '';
  5621. distInput.disabled = false;
  5622. distInput.value = '1';
  5623. ifaceSelect.disabled = false;
  5624. tableSelect.disabled = false;
  5625. commentInput.disabled = false;
  5626. commentInput.value = '';
  5627. disCheck.disabled = false;
  5628. disCheck.checked = false;
  5629. if (saveBtn) saveBtn.classList.remove('hidden');
  5630. const checkGw = document.getElementById('route-modal-check-gw');
  5631. if (checkGw) checkGw.value = 'internet';
  5632. const checkTarget = document.getElementById('route-modal-check-target');
  5633. if (checkTarget) checkTarget.value = '1.1.1.1';
  5634. const checkInterval = document.getElementById('route-modal-check-interval');
  5635. if (checkInterval) checkInterval.value = '5';
  5636. const checkThresh = document.getElementById('route-modal-check-threshold');
  5637. if (checkThresh) checkThresh.value = '3';
  5638. toggleRouteCheckModeUI();
  5639. populateInterfaceSelect('route-modal-iface');
  5640. // Populate tables
  5641. tableSelect.innerHTML = '';
  5642. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5643. const opt = document.createElement('option');
  5644. opt.value = t.name;
  5645. opt.innerText = t.name;
  5646. if (t.name === 'main') opt.selected = true;
  5647. tableSelect.appendChild(opt);
  5648. });
  5649. document.getElementById('route-modal').classList.remove('hidden');
  5650. }
  5651. function openEditRouteModal(id) {
  5652. const r = (state.routes || []).find(route => route.id === id);
  5653. if (!r) return;
  5654. const isStatic = !!r.static;
  5655. document.getElementById('route-modal-title').innerText = isStatic
  5656. ? `Edit Route: ${r.dst_address}`
  5657. : `Route Properties (Read Only): ${r.dst_address}`;
  5658. document.getElementById('route-modal-id').value = r.id;
  5659. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5660. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5661. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5662. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5663. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5664. const dstInput = document.getElementById('route-modal-dst');
  5665. const gwInput = document.getElementById('route-modal-gw');
  5666. const distInput = document.getElementById('route-modal-distance');
  5667. const ifaceSelect = document.getElementById('route-modal-iface');
  5668. const tableSelect = document.getElementById('route-modal-table');
  5669. const commentInput = document.getElementById('route-modal-comment');
  5670. const disCheck = document.getElementById('route-modal-disabled');
  5671. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5672. dstInput.value = r.dst_address;
  5673. gwInput.value = r.gateway || '';
  5674. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5675. commentInput.value = r.comment || '';
  5676. disCheck.checked = !!r.disabled;
  5677. const checkGw = document.getElementById('route-modal-check-gw');
  5678. if (checkGw) checkGw.value = r.check_gateway || 'none';
  5679. const checkTarget = document.getElementById('route-modal-check-target');
  5680. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  5681. const checkInterval = document.getElementById('route-modal-check-interval');
  5682. if (checkInterval) checkInterval.value = r.check_interval || 5;
  5683. const checkThresh = document.getElementById('route-modal-check-threshold');
  5684. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  5685. toggleRouteCheckModeUI();
  5686. dstInput.disabled = !isStatic;
  5687. gwInput.disabled = !isStatic;
  5688. distInput.disabled = !isStatic;
  5689. ifaceSelect.disabled = !isStatic;
  5690. tableSelect.disabled = !isStatic;
  5691. commentInput.disabled = !isStatic;
  5692. disCheck.disabled = !isStatic;
  5693. if (checkGw) checkGw.disabled = !isStatic;
  5694. if (checkTarget) checkTarget.disabled = !isStatic;
  5695. if (checkInterval) checkInterval.disabled = !isStatic;
  5696. if (checkThresh) checkThresh.disabled = !isStatic;
  5697. if (saveBtn) {
  5698. if (isStatic) {
  5699. saveBtn.classList.remove('hidden');
  5700. } else {
  5701. saveBtn.classList.add('hidden');
  5702. }
  5703. }
  5704. populateInterfaceSelect('route-modal-iface', r.interface);
  5705. tableSelect.innerHTML = '';
  5706. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5707. const opt = document.createElement('option');
  5708. opt.value = t.name;
  5709. opt.innerText = t.name;
  5710. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5711. tableSelect.appendChild(opt);
  5712. });
  5713. document.getElementById('route-modal').classList.remove('hidden');
  5714. }
  5715. function closeRouteModal() {
  5716. document.getElementById('route-modal').classList.add('hidden');
  5717. }
  5718. function setRouteCheckTarget(ip) {
  5719. const inp = document.getElementById('route-modal-check-target');
  5720. if (inp) inp.value = ip;
  5721. }
  5722. function toggleRouteCheckModeUI() {
  5723. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  5724. const targetRow = document.getElementById('route-row-check-target');
  5725. const paramsRow = document.getElementById('route-row-check-params');
  5726. if (mode === 'none') {
  5727. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5728. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  5729. } else if (mode === 'ping') {
  5730. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5731. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5732. } else { // internet
  5733. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  5734. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5735. }
  5736. }
  5737. async function submitSaveRoute(e) {
  5738. e.preventDefault();
  5739. const id = document.getElementById('route-modal-id').value;
  5740. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5741. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5742. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5743. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5744. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5745. const dst = document.getElementById('route-modal-dst').value.trim();
  5746. const gw = document.getElementById('route-modal-gw').value.trim();
  5747. const table = document.getElementById('route-modal-table').value;
  5748. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5749. const iface = document.getElementById('route-modal-iface').value;
  5750. const comment = document.getElementById('route-modal-comment').value.trim();
  5751. const disabled = document.getElementById('route-modal-disabled').checked;
  5752. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  5753. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  5754. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  5755. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  5756. if (!dst) {
  5757. showToast('Error', 'Destination address is required', 'error');
  5758. return;
  5759. }
  5760. if (!gw && !iface) {
  5761. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5762. return;
  5763. }
  5764. const payload = {
  5765. id,
  5766. old_dst_address: oldDst,
  5767. old_gateway: oldGw,
  5768. old_routing_table: oldTable,
  5769. old_interface: oldIface,
  5770. dst_address: dst,
  5771. gateway: gw || iface,
  5772. routing_table: table,
  5773. distance,
  5774. interface: iface,
  5775. comment,
  5776. disabled,
  5777. check_gateway,
  5778. check_target,
  5779. check_interval,
  5780. check_threshold
  5781. };
  5782. if (oldDistStr !== undefined && oldDistStr !== '') {
  5783. payload.old_distance = parseInt(oldDistStr, 10);
  5784. }
  5785. try {
  5786. const res = await fetch(`${API_BASE}/routes`, {
  5787. method: 'POST',
  5788. headers: { 'Content-Type': 'application/json' },
  5789. body: JSON.stringify(payload)
  5790. });
  5791. if (res.ok) {
  5792. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5793. closeRouteModal();
  5794. loadRoutes();
  5795. } else {
  5796. const err = await res.json();
  5797. showToast('Error', err.message || 'Failed to save route', 'error');
  5798. }
  5799. } catch (err) {
  5800. showToast('Error', err.message, 'error');
  5801. }
  5802. }
  5803. async function toggleRouteState(id, disabled) {
  5804. try {
  5805. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5806. method: 'POST',
  5807. headers: { 'Content-Type': 'application/json' },
  5808. body: JSON.stringify({ disabled })
  5809. });
  5810. if (res.ok) loadRoutes();
  5811. } catch (err) {
  5812. showToast('Error', err.message, 'error');
  5813. }
  5814. }
  5815. async function deleteRoute(id) {
  5816. if (!confirm('Are you sure you want to delete this route?')) return;
  5817. try {
  5818. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5819. if (res.ok) {
  5820. showToast('Deleted', 'Route removed', 'success');
  5821. loadRoutes();
  5822. }
  5823. } catch (err) {
  5824. showToast('Error', err.message, 'error');
  5825. }
  5826. }
  5827. // ----------------- Policy Rules (/ip route rule) -----------------
  5828. function renderPolicyRules() {
  5829. const tbody = document.getElementById('rules-table-body');
  5830. const empty = document.getElementById('rules-empty');
  5831. if (!tbody) return;
  5832. tbody.innerHTML = '';
  5833. const showSystem = document.getElementById('prule-show-system')?.checked;
  5834. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5835. const countBadge = document.getElementById('rules-count-badge');
  5836. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5837. const bRules = document.getElementById('routes-badge-rules');
  5838. if (bRules) bRules.innerText = filtered.length;
  5839. if (filtered.length === 0) {
  5840. empty?.classList.remove('hidden');
  5841. return;
  5842. }
  5843. empty?.classList.add('hidden');
  5844. filtered.forEach(pr => {
  5845. const isSys = pr.is_default || pr.is_system;
  5846. const tr = document.createElement('tr');
  5847. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5848. tr.innerHTML = `
  5849. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5850. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5851. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5852. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5853. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5854. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5855. <td class="py-2.5 px-3 text-right font-sans">
  5856. ${!pr.is_default ? `
  5857. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5858. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5859. </td>
  5860. `;
  5861. tbody.appendChild(tr);
  5862. });
  5863. }
  5864. function openAddPolicyRuleModal() {
  5865. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5866. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5867. document.getElementById('prule-modal-mark').value = '';
  5868. document.getElementById('prule-modal-src').value = '';
  5869. document.getElementById('prule-modal-dst').value = '';
  5870. const sel = document.getElementById('prule-modal-table');
  5871. sel.innerHTML = '';
  5872. (state.routingTables || []).forEach(t => {
  5873. const opt = document.createElement('option');
  5874. opt.value = t.name;
  5875. opt.innerText = t.name;
  5876. sel.appendChild(opt);
  5877. });
  5878. document.getElementById('prule-modal').classList.remove('hidden');
  5879. }
  5880. function closePolicyRuleModal() {
  5881. document.getElementById('prule-modal').classList.add('hidden');
  5882. }
  5883. async function submitSavePolicyRule(e) {
  5884. e.preventDefault();
  5885. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5886. const mark = document.getElementById('prule-modal-mark').value.trim();
  5887. const src = document.getElementById('prule-modal-src').value.trim();
  5888. const dst = document.getElementById('prule-modal-dst').value.trim();
  5889. const table = document.getElementById('prule-modal-table').value;
  5890. const action = document.getElementById('prule-modal-action').value;
  5891. try {
  5892. const res = await fetch(`${API_BASE}/routing/rules`, {
  5893. method: 'POST',
  5894. headers: { 'Content-Type': 'application/json' },
  5895. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5896. });
  5897. if (res.ok) {
  5898. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5899. closePolicyRuleModal();
  5900. loadRoutes();
  5901. } else {
  5902. const err = await res.json();
  5903. showToast('Error', err.message, 'error');
  5904. }
  5905. } catch (err) {
  5906. showToast('Error', err.message, 'error');
  5907. }
  5908. }
  5909. async function deletePolicyRule(id) {
  5910. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5911. try {
  5912. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5913. if (res.ok) {
  5914. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5915. loadRoutes();
  5916. }
  5917. } catch (err) {
  5918. showToast('Error', err.message, 'error');
  5919. }
  5920. }
  5921. // ----------------- Routing Tables -----------------
  5922. function renderRoutingTables() {
  5923. const tbody = document.getElementById('tables-table-body');
  5924. if (!tbody) return;
  5925. tbody.innerHTML = '';
  5926. (state.routingTables || []).forEach(t => {
  5927. const tr = document.createElement('tr');
  5928. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5929. tr.innerHTML = `
  5930. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5931. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5932. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5933. `;
  5934. tbody.appendChild(tr);
  5935. });
  5936. }
  5937. function openAddTableModal() {
  5938. document.getElementById('table-modal-name').value = '';
  5939. document.getElementById('table-modal-id').value = '';
  5940. document.getElementById('table-modal-comment').value = '';
  5941. document.getElementById('table-modal').classList.remove('hidden');
  5942. }
  5943. function closeTableModal() {
  5944. document.getElementById('table-modal').classList.add('hidden');
  5945. }
  5946. async function submitSaveTable(e) {
  5947. e.preventDefault();
  5948. const name = document.getElementById('table-modal-name').value.trim();
  5949. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5950. const comment = document.getElementById('table-modal-comment').value.trim();
  5951. try {
  5952. const res = await fetch(`${API_BASE}/routing/tables`, {
  5953. method: 'POST',
  5954. headers: { 'Content-Type': 'application/json' },
  5955. body: JSON.stringify({ name, table_id: id, comment })
  5956. });
  5957. if (res.ok) {
  5958. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5959. closeTableModal();
  5960. loadRoutes();
  5961. } else {
  5962. const err = await res.json();
  5963. showToast('Error', err.message, 'error');
  5964. }
  5965. } catch (err) {
  5966. showToast('Error', err.message, 'error');
  5967. }
  5968. }
  5969. async function loadDebianConfig() {
  5970. const view = document.getElementById('debian-config-view');
  5971. view.innerText = 'Generating live configuration...';
  5972. try {
  5973. const res = await fetch(`${API_BASE}/debian/config`);
  5974. const data = await res.json();
  5975. view.innerText = data.content || '# Empty config';
  5976. } catch (err) {
  5977. view.innerText = 'Failed to generate Debian network config.';
  5978. }
  5979. }
  5980. async function saveDebianConfig() {
  5981. try {
  5982. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5983. const data = await res.json();
  5984. if (res.ok) {
  5985. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5986. loadDebianConfig();
  5987. }
  5988. } catch (err) {
  5989. showToast('Error', err.message, 'error');
  5990. }
  5991. }
  5992. function showToast(title, message, type = 'info') {
  5993. const container = document.getElementById('toast-container');
  5994. const toast = document.createElement('div');
  5995. const borderColors = {
  5996. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5997. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5998. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5999. };
  6000. 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}`;
  6001. toast.innerHTML = `
  6002. <div class="flex-1">
  6003. <div class="font-bold text-xs text-white">${title}</div>
  6004. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6005. </div>
  6006. `;
  6007. container.appendChild(toast);
  6008. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6009. setTimeout(() => {
  6010. toast.classList.add('opacity-0', 'translate-y-2');
  6011. setTimeout(() => toast.remove(), 300);
  6012. }, 4000);
  6013. }
  6014. function formatTraffic(bytesPerSec) {
  6015. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6016. const kb = bytesPerSec / 1024;
  6017. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6018. const mb = kb / 1024;
  6019. return `${mb.toFixed(2)} MB/s`;
  6020. }
  6021. function toggleSidebar() {
  6022. const sb = document.getElementById('sidebar');
  6023. sb.classList.toggle('-translate-x-full');
  6024. }
  6025. // ======================== EoIP (Ethernet over IP) ========================
  6026. async function loadEoIP(populate = true) {
  6027. try {
  6028. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6029. const data = await res.json();
  6030. state.eoipTunnels = Array.isArray(data) ? data : [];
  6031. const badge = document.getElementById('eoip-count-badge');
  6032. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6033. const sideBadge = document.getElementById('badge-eoip-count');
  6034. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6035. renderEoIPTunnels();
  6036. } catch (err) {
  6037. console.error('Failed to load EoIP:', err);
  6038. }
  6039. }
  6040. function renderEoIPTunnels() {
  6041. const tbody = document.getElementById('eoip-table-body');
  6042. const empty = document.getElementById('eoip-empty');
  6043. if (!tbody) return;
  6044. tbody.innerHTML = '';
  6045. const tunnels = state.eoipTunnels || [];
  6046. if (tunnels.length === 0) {
  6047. empty?.classList.remove('hidden');
  6048. return;
  6049. }
  6050. empty?.classList.add('hidden');
  6051. tunnels.forEach(t => {
  6052. const tr = document.createElement('tr');
  6053. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6054. tr.innerHTML = `
  6055. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6056. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6057. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6058. <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>
  6059. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6060. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6061. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6062. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6063. <td class="py-2.5 px-3 font-mono text-[11px]">
  6064. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6065. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6066. </td>
  6067. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6068. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6069. <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>
  6070. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6071. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6072. </td>
  6073. `;
  6074. tbody.appendChild(tr);
  6075. });
  6076. }
  6077. function openAddEoIPModal() {
  6078. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6079. document.getElementById('eoip-modal-id').value = '';
  6080. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6081. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6082. document.getElementById('eoip-modal-remote').value = '';
  6083. document.getElementById('eoip-modal-ip').value = '';
  6084. document.getElementById('eoip-modal-local').value = '';
  6085. document.getElementById('eoip-modal-mac').value = '';
  6086. document.getElementById('eoip-modal-mtu').value = '1500';
  6087. document.getElementById('eoip-modal-comment').value = '';
  6088. document.getElementById('eoip-modal-clampmss').checked = true;
  6089. document.getElementById('eoip-modal-disabled').checked = false;
  6090. document.getElementById('eoip-modal').classList.remove('hidden');
  6091. }
  6092. function openEditEoIPModal(id) {
  6093. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6094. if (!t) return;
  6095. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6096. document.getElementById('eoip-modal-id').value = t.id;
  6097. document.getElementById('eoip-modal-name').value = t.name;
  6098. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6099. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6100. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6101. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6102. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6103. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6104. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6105. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6106. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6107. document.getElementById('eoip-modal').classList.remove('hidden');
  6108. }
  6109. function closeEoIPModal() {
  6110. document.getElementById('eoip-modal').classList.add('hidden');
  6111. }
  6112. async function submitSaveEoIP(e) {
  6113. e.preventDefault();
  6114. const id = document.getElementById('eoip-modal-id').value;
  6115. const name = document.getElementById('eoip-modal-name').value.trim();
  6116. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6117. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6118. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6119. const local = document.getElementById('eoip-modal-local').value.trim();
  6120. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6121. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6122. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6123. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6124. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6125. try {
  6126. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6127. method: 'POST',
  6128. headers: { 'Content-Type': 'application/json' },
  6129. body: JSON.stringify({
  6130. id,
  6131. name,
  6132. tunnel_id: tunnelId,
  6133. remote_address: remote,
  6134. ip_address: ipAddress,
  6135. local_address: local,
  6136. mac_address: mac,
  6137. mtu,
  6138. clamp_mss: clampMss,
  6139. comment,
  6140. disabled
  6141. })
  6142. });
  6143. if (res.ok) {
  6144. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6145. closeEoIPModal();
  6146. loadEoIP(false);
  6147. fetchData(false);
  6148. } else {
  6149. const err = await res.json();
  6150. showToast('Error', err.message, 'error');
  6151. }
  6152. } catch (err) {
  6153. showToast('Error', err.message, 'error');
  6154. }
  6155. }
  6156. async function toggleEoIPState(id, disabled) {
  6157. try {
  6158. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6159. method: 'POST',
  6160. headers: { 'Content-Type': 'application/json' },
  6161. body: JSON.stringify({ disabled })
  6162. });
  6163. if (res.ok) {
  6164. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6165. loadEoIP(false);
  6166. fetchData(false);
  6167. }
  6168. } catch (err) {
  6169. showToast('Error', err.message, 'error');
  6170. }
  6171. }
  6172. async function deleteEoIP(id) {
  6173. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6174. try {
  6175. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6176. if (res.ok) {
  6177. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6178. loadEoIP(false);
  6179. fetchData(false);
  6180. }
  6181. } catch (err) {
  6182. showToast('Error', err.message, 'error');
  6183. }
  6184. }
  6185. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6186. async function loadAeroTUN(populate = true) {
  6187. try {
  6188. const [tunnelsRes, statsRes] = await Promise.all([
  6189. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6190. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6191. ]);
  6192. if (tunnelsRes.ok) {
  6193. const data = await tunnelsRes.json();
  6194. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6195. }
  6196. if (statsRes.ok) {
  6197. state.aerotunStats = await statsRes.json();
  6198. }
  6199. const countBadge = document.getElementById('aerotun-count-badge');
  6200. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6201. const sideBadge = document.getElementById('badge-aerotun-count');
  6202. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6203. renderAeroTUN();
  6204. } catch (err) {
  6205. console.error('Failed to load AeroTUN:', err);
  6206. }
  6207. }
  6208. function renderAeroTUN() {
  6209. const tbody = document.getElementById('aerotun-table-body');
  6210. const empty = document.getElementById('aerotun-empty');
  6211. // Update summary cards
  6212. const stats = state.aerotunStats || {};
  6213. const tunnels = state.aerotunTunnels || [];
  6214. const statActive = document.getElementById('aerotun-stat-active');
  6215. if (statActive) {
  6216. const activeCount = tunnels.filter(t => t.running).length;
  6217. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6218. }
  6219. const statSaved = document.getElementById('aerotun-stat-saved');
  6220. if (statSaved) {
  6221. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6222. }
  6223. const statRatio = document.getElementById('aerotun-stat-ratio');
  6224. if (statRatio) {
  6225. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6226. }
  6227. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6228. if (statTraffic) {
  6229. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6230. }
  6231. if (!tbody) return;
  6232. tbody.innerHTML = '';
  6233. if (tunnels.length === 0) {
  6234. empty?.classList.remove('hidden');
  6235. return;
  6236. }
  6237. empty?.classList.add('hidden');
  6238. tunnels.forEach(t => {
  6239. const tr = document.createElement('tr');
  6240. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6241. const modeBadge = t.mode === 'server'
  6242. ? `<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>`
  6243. : `<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>`;
  6244. const endpointInfo = t.mode === 'server'
  6245. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6246. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6247. const compBadge = t.compression
  6248. ? `<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>`
  6249. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6250. const activePeer = t.active_peer_endpoint
  6251. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6252. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6253. const rawRx = formatBytes(t.rx_bytes || 0);
  6254. const rawTx = formatBytes(t.tx_bytes || 0);
  6255. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6256. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6257. tr.innerHTML = `
  6258. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6259. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6260. <span>${escapeHtml(t.name)}</span>
  6261. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6262. </td>
  6263. <td class="py-2.5 px-3">${modeBadge}</td>
  6264. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6265. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6266. <td class="py-2.5 px-3">${compBadge}</td>
  6267. <td class="py-2.5 px-3">${activePeer}</td>
  6268. <td class="py-2.5 px-3 font-mono text-[11px]">
  6269. <span class="text-emerald-400">↓ ${rawRx}</span>
  6270. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6271. </td>
  6272. <td class="py-2.5 px-3 font-mono text-[11px]">
  6273. <span class="text-slate-400">↓ ${wireRx}</span>
  6274. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6275. </td>
  6276. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6277. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6278. ${t.running
  6279. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6280. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6281. }
  6282. <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>
  6283. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6284. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6285. </td>
  6286. `;
  6287. tbody.appendChild(tr);
  6288. });
  6289. }
  6290. function onAeroTUNModeChange() {
  6291. const mode = document.getElementById('aerotun-modal-mode').value;
  6292. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6293. const portInput = document.getElementById('aerotun-modal-port');
  6294. if (mode === 'server') {
  6295. if (!portInput.value) portInput.value = '51830';
  6296. endpointInput.placeholder = 'Optional / learned roaming peer';
  6297. } else {
  6298. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6299. if (!portInput.value) portInput.value = '';
  6300. }
  6301. }
  6302. async function generateAeroTUNKey() {
  6303. try {
  6304. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6305. if (res.ok) {
  6306. const data = await res.json();
  6307. document.getElementById('aerotun-modal-psk').value = data.key;
  6308. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6309. }
  6310. } catch (err) {
  6311. const arr = new Uint8Array(32);
  6312. crypto.getRandomValues(arr);
  6313. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6314. document.getElementById('aerotun-modal-psk').value = hex;
  6315. }
  6316. }
  6317. function openAddAeroTUNModal() {
  6318. const tunnels = state.aerotunTunnels || [];
  6319. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6320. document.getElementById('aerotun-modal-id').value = '';
  6321. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6322. document.getElementById('aerotun-modal-mode').value = 'server';
  6323. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6324. document.getElementById('aerotun-modal-endpoint').value = '';
  6325. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6326. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6327. document.getElementById('aerotun-modal-psk').value = '';
  6328. document.getElementById('aerotun-modal-mtu').value = '1420';
  6329. document.getElementById('aerotun-modal-comment').value = '';
  6330. document.getElementById('aerotun-modal-compression').checked = true;
  6331. document.getElementById('aerotun-modal-defroute').checked = false;
  6332. document.getElementById('aerotun-modal-disabled').checked = false;
  6333. generateAeroTUNKey();
  6334. onAeroTUNModeChange();
  6335. document.getElementById('aerotun-modal').classList.remove('hidden');
  6336. }
  6337. function openEditAeroTUNModal(id) {
  6338. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6339. if (!t) return;
  6340. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6341. document.getElementById('aerotun-modal-id').value = t.id;
  6342. document.getElementById('aerotun-modal-name').value = t.name;
  6343. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6344. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6345. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6346. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6347. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6348. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6349. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6350. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6351. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6352. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6353. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6354. onAeroTUNModeChange();
  6355. document.getElementById('aerotun-modal').classList.remove('hidden');
  6356. }
  6357. function closeAeroTUNModal() {
  6358. document.getElementById('aerotun-modal').classList.add('hidden');
  6359. }
  6360. async function submitSaveAeroTUN(e) {
  6361. e.preventDefault();
  6362. const id = document.getElementById('aerotun-modal-id').value;
  6363. const name = document.getElementById('aerotun-modal-name').value.trim();
  6364. const mode = document.getElementById('aerotun-modal-mode').value;
  6365. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6366. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6367. const local = document.getElementById('aerotun-modal-local').value.trim();
  6368. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6369. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6370. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6371. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6372. const compression = document.getElementById('aerotun-modal-compression').checked;
  6373. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6374. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6375. if (mode === 'client' && !endpoint) {
  6376. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6377. return;
  6378. }
  6379. if (!psk) {
  6380. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6381. return;
  6382. }
  6383. try {
  6384. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6385. method: 'POST',
  6386. headers: { 'Content-Type': 'application/json' },
  6387. body: JSON.stringify({
  6388. id,
  6389. name,
  6390. mode,
  6391. listen_port: port,
  6392. remote_endpoint: endpoint,
  6393. local_address: local,
  6394. peer_address: peer,
  6395. psk,
  6396. mtu,
  6397. compression,
  6398. default_route: defaultRoute,
  6399. comment,
  6400. disabled
  6401. })
  6402. });
  6403. if (res.ok) {
  6404. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6405. closeAeroTUNModal();
  6406. loadAeroTUN(false);
  6407. fetchData(false);
  6408. } else {
  6409. const err = await res.text();
  6410. showToast('Error Saving Tunnel', err, 'error');
  6411. }
  6412. } catch (err) {
  6413. showToast('Network Error', err.message, 'error');
  6414. }
  6415. }
  6416. async function startAeroTUNTunnel(id) {
  6417. try {
  6418. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6419. if (res.ok) {
  6420. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6421. loadAeroTUN(false);
  6422. fetchData(false);
  6423. } else {
  6424. const err = await res.text();
  6425. showToast('Failed to Start', err, 'error');
  6426. }
  6427. } catch (err) {
  6428. showToast('Error', err.message, 'error');
  6429. }
  6430. }
  6431. async function stopAeroTUNTunnel(id) {
  6432. try {
  6433. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6434. if (res.ok) {
  6435. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6436. loadAeroTUN(false);
  6437. fetchData(false);
  6438. } else {
  6439. const err = await res.text();
  6440. showToast('Failed to Stop', err, 'error');
  6441. }
  6442. } catch (err) {
  6443. showToast('Error', err.message, 'error');
  6444. }
  6445. }
  6446. async function toggleAeroTUNState(id, disabled) {
  6447. try {
  6448. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6449. method: 'POST',
  6450. headers: { 'Content-Type': 'application/json' },
  6451. body: JSON.stringify({ disabled })
  6452. });
  6453. if (res.ok) {
  6454. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6455. loadAeroTUN(false);
  6456. fetchData(false);
  6457. }
  6458. } catch (err) {
  6459. showToast('Error', err.message, 'error');
  6460. }
  6461. }
  6462. async function deleteAeroTUN(id) {
  6463. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6464. try {
  6465. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6466. if (res.ok) {
  6467. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6468. loadAeroTUN(false);
  6469. fetchData(false);
  6470. }
  6471. } catch (err) {
  6472. showToast('Error', err.message, 'error');
  6473. }
  6474. }
  6475. // ======================== PPP Central Hub & Servers ========================
  6476. function switchPPPSubTab(tab) {
  6477. state.pppSubTab = tab;
  6478. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6479. tabs.forEach(t => {
  6480. const panel = document.getElementById(`ppp-subtab-${t}`);
  6481. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6482. if (panel) {
  6483. if (t === tab) panel.classList.remove('hidden');
  6484. else panel.classList.add('hidden');
  6485. }
  6486. if (btn) {
  6487. if (t === tab) {
  6488. 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';
  6489. } else {
  6490. 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';
  6491. }
  6492. }
  6493. });
  6494. const addBtn = document.getElementById('ppp-primary-add-btn');
  6495. if (addBtn) {
  6496. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6497. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6498. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6499. else addBtn.innerHTML = '<span>Save Config</span>';
  6500. }
  6501. if (tab === 'active') loadPPPSessions();
  6502. }
  6503. function openCurrentPPPModal() {
  6504. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6505. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6506. else if (state.pppSubTab === 'active') loadPPPSessions();
  6507. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6508. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6509. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6510. }
  6511. async function loadPPP(populateDropdowns = true) {
  6512. await Promise.all([
  6513. loadPPPSecrets(),
  6514. loadPPPProfiles(),
  6515. loadPPPServers(),
  6516. loadPPPSessions()
  6517. ]);
  6518. }
  6519. async function loadPPPSecrets() {
  6520. try {
  6521. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6522. const data = await res.json();
  6523. state.pppSecrets = Array.isArray(data) ? data : [];
  6524. const b = document.getElementById('ppp-badge-secrets');
  6525. if (b) b.innerText = state.pppSecrets.length;
  6526. const b2 = document.getElementById('secrets-count-badge');
  6527. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6528. renderPPPSecrets();
  6529. } catch (err) {
  6530. console.error('Failed to load PPP secrets:', err);
  6531. }
  6532. }
  6533. function renderPPPSecrets() {
  6534. const tbody = document.getElementById('secrets-table-body');
  6535. const empty = document.getElementById('secrets-empty');
  6536. if (!tbody) return;
  6537. tbody.innerHTML = '';
  6538. const secrets = state.pppSecrets || [];
  6539. if (secrets.length === 0) {
  6540. empty?.classList.remove('hidden');
  6541. return;
  6542. }
  6543. empty?.classList.add('hidden');
  6544. secrets.forEach(s => {
  6545. const tr = document.createElement('tr');
  6546. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6547. tr.innerHTML = `
  6548. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6549. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6550. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6551. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6552. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6553. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6554. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6555. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6556. <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>
  6557. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6558. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6559. </td>
  6560. `;
  6561. tbody.appendChild(tr);
  6562. });
  6563. }
  6564. async function loadPPPProfiles() {
  6565. try {
  6566. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6567. const data = await res.json();
  6568. state.pppProfiles = Array.isArray(data) ? data : [];
  6569. const b = document.getElementById('ppp-badge-profiles');
  6570. if (b) b.innerText = state.pppProfiles.length;
  6571. const b2 = document.getElementById('profiles-count-badge');
  6572. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6573. // Populate profile selects across modals
  6574. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6575. selects.forEach(sid => {
  6576. const el = document.getElementById(sid);
  6577. if (!el) return;
  6578. const cur = el.value;
  6579. el.innerHTML = '';
  6580. state.pppProfiles.forEach(p => {
  6581. const opt = document.createElement('option');
  6582. opt.value = p.name;
  6583. opt.innerText = `${p.name} (${p.remote_address})`;
  6584. if (p.name === cur) opt.selected = true;
  6585. el.appendChild(opt);
  6586. });
  6587. });
  6588. renderPPPProfiles();
  6589. } catch (err) {
  6590. console.error('Failed to load PPP profiles:', err);
  6591. }
  6592. }
  6593. function renderPPPProfiles() {
  6594. const tbody = document.getElementById('profiles-table-body');
  6595. if (!tbody) return;
  6596. tbody.innerHTML = '';
  6597. (state.pppProfiles || []).forEach(p => {
  6598. const isDefault = p.name.startsWith('default');
  6599. const tr = document.createElement('tr');
  6600. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6601. tr.innerHTML = `
  6602. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6603. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6604. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6605. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6606. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6607. <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>
  6608. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6609. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6610. ${!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>`}
  6611. </td>
  6612. `;
  6613. tbody.appendChild(tr);
  6614. });
  6615. }
  6616. async function loadPPPServers() {
  6617. try {
  6618. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6619. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6620. fetch(`${API_BASE}/vpn/servers/pptp`),
  6621. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6622. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6623. ]);
  6624. if (pppoeRes.ok) {
  6625. state.pppoeServer = await pppoeRes.json();
  6626. const s = state.pppoeServer;
  6627. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6628. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6629. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6630. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6631. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6632. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6633. const pill = document.getElementById('pppoe-server-status-pill');
  6634. if (pill) {
  6635. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6636. 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';
  6637. }
  6638. setDotBadge('ppp-badge-pppoe-state', s.running);
  6639. }
  6640. if (pptpRes.ok) {
  6641. state.pptpServer = await pptpRes.json();
  6642. const s = state.pptpServer;
  6643. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6644. document.getElementById('pptp-server-port').value = s.port || 1723;
  6645. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6646. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6647. const pill = document.getElementById('pptp-server-status-pill');
  6648. if (pill) {
  6649. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6650. 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';
  6651. }
  6652. setDotBadge('ppp-badge-pptp-state', s.running);
  6653. }
  6654. if (l2tpRes.ok) {
  6655. state.l2tpServer = await l2tpRes.json();
  6656. const s = state.l2tpServer;
  6657. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6658. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6659. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6660. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6661. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6662. const pill = document.getElementById('l2tp-server-status-pill');
  6663. if (pill) {
  6664. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6665. 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';
  6666. }
  6667. setDotBadge('ppp-badge-l2tp-state', s.running);
  6668. }
  6669. if (ipsecRes.ok) {
  6670. state.ipsecServer = await ipsecRes.json();
  6671. const s = state.ipsecServer;
  6672. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6673. if (modalEn) modalEn.checked = !!s.enabled;
  6674. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6675. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6676. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6677. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6678. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6679. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6680. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6681. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6682. const pill = document.getElementById('modal-ipsec-server-status');
  6683. if (pill) {
  6684. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6685. 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';
  6686. }
  6687. }
  6688. } catch (err) {
  6689. console.error('Failed to load VPN servers:', err);
  6690. }
  6691. }
  6692. async function loadPPPSessions() {
  6693. try {
  6694. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6695. const data = await res.json();
  6696. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6697. const b = document.getElementById('ppp-badge-active');
  6698. if (b) b.innerText = state.pppActiveSessions.length;
  6699. const sideB = document.getElementById('badge-ppp-sessions');
  6700. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6701. renderPPPSessions();
  6702. } catch (err) {
  6703. console.error('Failed to load active PPP sessions:', err);
  6704. }
  6705. }
  6706. function renderPPPSessions() {
  6707. const tbody = document.getElementById('active-ppp-table-body');
  6708. const empty = document.getElementById('active-ppp-empty');
  6709. if (!tbody) return;
  6710. tbody.innerHTML = '';
  6711. const list = state.pppActiveSessions || [];
  6712. if (list.length === 0) {
  6713. empty?.classList.remove('hidden');
  6714. return;
  6715. }
  6716. empty?.classList.add('hidden');
  6717. list.forEach(s => {
  6718. const tr = document.createElement('tr');
  6719. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6720. tr.innerHTML = `
  6721. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6722. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6723. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6724. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6725. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6726. <td class="py-2.5 px-3 text-[11px]">
  6727. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6728. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6729. </td>
  6730. <td class="py-2.5 px-3 text-right font-sans">
  6731. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6732. </td>
  6733. `;
  6734. tbody.appendChild(tr);
  6735. });
  6736. }
  6737. async function disconnectPPPSession(iface) {
  6738. if (!confirm(`Disconnect session ${iface}?`)) return;
  6739. try {
  6740. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6741. if (res.ok) {
  6742. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6743. loadPPPSessions();
  6744. }
  6745. } catch (err) {
  6746. showToast('Error', err.message, 'error');
  6747. }
  6748. }
  6749. // PPP Secret Modal handlers
  6750. function openAddPPPSecretModal() {
  6751. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6752. document.getElementById('secret-modal-id').value = '';
  6753. document.getElementById('secret-modal-name').value = '';
  6754. document.getElementById('secret-modal-password').value = '';
  6755. document.getElementById('secret-modal-service').value = 'any';
  6756. document.getElementById('secret-modal-profile').value = 'default';
  6757. document.getElementById('secret-modal-local').value = '';
  6758. document.getElementById('secret-modal-remote').value = '';
  6759. document.getElementById('secret-modal-comment').value = '';
  6760. document.getElementById('secret-modal-disabled').checked = false;
  6761. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6762. }
  6763. function openEditPPPSecretModal(id) {
  6764. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6765. if (!s) return;
  6766. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6767. document.getElementById('secret-modal-id').value = s.id;
  6768. document.getElementById('secret-modal-name').value = s.name;
  6769. document.getElementById('secret-modal-password').value = s.password;
  6770. document.getElementById('secret-modal-service').value = s.service || 'any';
  6771. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6772. document.getElementById('secret-modal-local').value = s.local_address || '';
  6773. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6774. document.getElementById('secret-modal-comment').value = s.comment || '';
  6775. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6776. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6777. }
  6778. function closePPPSecretModal() {
  6779. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6780. }
  6781. async function submitSavePPPSecret(e) {
  6782. e.preventDefault();
  6783. const id = document.getElementById('secret-modal-id').value;
  6784. const name = document.getElementById('secret-modal-name').value.trim();
  6785. const password = document.getElementById('secret-modal-password').value.trim();
  6786. const service = document.getElementById('secret-modal-service').value;
  6787. const profile = document.getElementById('secret-modal-profile').value;
  6788. const local = document.getElementById('secret-modal-local').value.trim();
  6789. const remote = document.getElementById('secret-modal-remote').value.trim();
  6790. const comment = document.getElementById('secret-modal-comment').value.trim();
  6791. const disabled = document.getElementById('secret-modal-disabled').checked;
  6792. try {
  6793. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6794. method: 'POST',
  6795. headers: { 'Content-Type': 'application/json' },
  6796. body: JSON.stringify({
  6797. id,
  6798. name,
  6799. password,
  6800. service,
  6801. profile,
  6802. local_address: local,
  6803. remote_address: remote,
  6804. comment,
  6805. disabled
  6806. })
  6807. });
  6808. if (res.ok) {
  6809. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6810. closePPPSecretModal();
  6811. loadPPPSecrets();
  6812. } else {
  6813. const err = await res.json();
  6814. showToast('Error', err.message, 'error');
  6815. }
  6816. } catch (err) {
  6817. showToast('Error', err.message, 'error');
  6818. }
  6819. }
  6820. async function togglePPPSecretState(id, disabled) {
  6821. try {
  6822. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6823. method: 'POST',
  6824. headers: { 'Content-Type': 'application/json' },
  6825. body: JSON.stringify({ disabled })
  6826. });
  6827. if (res.ok) {
  6828. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6829. loadPPPSecrets();
  6830. }
  6831. } catch (err) {
  6832. showToast('Error', err.message, 'error');
  6833. }
  6834. }
  6835. async function deletePPPSecret(id) {
  6836. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6837. try {
  6838. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6839. if (res.ok) {
  6840. showToast('Deleted', 'Secret account removed', 'success');
  6841. loadPPPSecrets();
  6842. }
  6843. } catch (err) {
  6844. showToast('Error', err.message, 'error');
  6845. }
  6846. }
  6847. // PPP Profile Modal handlers
  6848. function openAddPPPProfileModal() {
  6849. document.getElementById('profile-modal-name').value = '';
  6850. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6851. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6852. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6853. document.getElementById('profile-modal-encryption').value = 'required';
  6854. document.getElementById('profile-modal-onlyone').checked = true;
  6855. document.getElementById('profile-modal-comment').value = '';
  6856. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6857. }
  6858. function closePPPProfileModal() {
  6859. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6860. }
  6861. async function submitSavePPPProfile(e) {
  6862. e.preventDefault();
  6863. const name = document.getElementById('profile-modal-name').value.trim();
  6864. const local = document.getElementById('profile-modal-local').value.trim();
  6865. const remote = document.getElementById('profile-modal-remote').value.trim();
  6866. const dns = document.getElementById('profile-modal-dns').value.trim();
  6867. const enc = document.getElementById('profile-modal-encryption').value;
  6868. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6869. const comment = document.getElementById('profile-modal-comment').value.trim();
  6870. try {
  6871. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6872. method: 'POST',
  6873. headers: { 'Content-Type': 'application/json' },
  6874. body: JSON.stringify({
  6875. id: name,
  6876. name,
  6877. local_address: local,
  6878. remote_address: remote,
  6879. dns_servers: dns,
  6880. use_encryption: enc,
  6881. only_one: onlyone,
  6882. comment
  6883. })
  6884. });
  6885. if (res.ok) {
  6886. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6887. closePPPProfileModal();
  6888. loadPPPProfiles();
  6889. } else {
  6890. const err = await res.json();
  6891. showToast('Error', err.message, 'error');
  6892. }
  6893. } catch (err) {
  6894. showToast('Error', err.message, 'error');
  6895. }
  6896. }
  6897. async function deletePPPProfile(name) {
  6898. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6899. try {
  6900. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6901. if (res.ok) {
  6902. showToast('Deleted', 'Profile removed', 'success');
  6903. loadPPPProfiles();
  6904. } else {
  6905. const err = await res.json();
  6906. showToast('Error', err.message, 'error');
  6907. }
  6908. } catch (err) {
  6909. showToast('Error', err.message, 'error');
  6910. }
  6911. }
  6912. // Server Config submissions
  6913. async function savePPPoEServerConfig(e) {
  6914. e.preventDefault();
  6915. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6916. const name = document.getElementById('pppoe-server-name').value.trim();
  6917. const iface = document.getElementById('pppoe-server-iface').value;
  6918. const profile = document.getElementById('pppoe-server-profile').value;
  6919. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6920. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6921. try {
  6922. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6923. method: 'POST',
  6924. headers: { 'Content-Type': 'application/json' },
  6925. body: JSON.stringify({
  6926. enabled,
  6927. service_name: name,
  6928. interface: iface,
  6929. default_profile: profile,
  6930. max_mtu: mtu,
  6931. max_mru: mtu,
  6932. one_session_per_host: onesession
  6933. })
  6934. });
  6935. if (res.ok) {
  6936. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6937. loadPPPServers();
  6938. fetchData(false);
  6939. } else {
  6940. const err = await res.json();
  6941. showToast('Error', err.message, 'error');
  6942. }
  6943. } catch (err) {
  6944. showToast('Error', err.message, 'error');
  6945. }
  6946. }
  6947. async function savePPTPServerConfig(e) {
  6948. e.preventDefault();
  6949. const enabled = document.getElementById('pptp-server-enabled').checked;
  6950. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6951. const profile = document.getElementById('pptp-server-profile').value;
  6952. const mppe = document.getElementById('pptp-server-mppe').checked;
  6953. try {
  6954. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6955. method: 'POST',
  6956. headers: { 'Content-Type': 'application/json' },
  6957. body: JSON.stringify({
  6958. enabled,
  6959. port,
  6960. default_profile: profile,
  6961. require_mppe: mppe
  6962. })
  6963. });
  6964. if (res.ok) {
  6965. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6966. loadPPPServers();
  6967. fetchData(false);
  6968. } else {
  6969. const err = await res.json();
  6970. showToast('Error', err.message, 'error');
  6971. }
  6972. } catch (err) {
  6973. showToast('Error', err.message, 'error');
  6974. }
  6975. }
  6976. async function saveL2TPServerConfig(e) {
  6977. e.preventDefault();
  6978. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6979. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6980. const profile = document.getElementById('l2tp-server-profile').value;
  6981. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6982. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6983. try {
  6984. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6985. method: 'POST',
  6986. headers: { 'Content-Type': 'application/json' },
  6987. body: JSON.stringify({
  6988. enabled,
  6989. port,
  6990. default_profile: profile,
  6991. use_ipsec: useipsec,
  6992. ipsec_secret: psk
  6993. })
  6994. });
  6995. if (res.ok) {
  6996. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6997. loadPPPServers();
  6998. fetchData(false);
  6999. } else {
  7000. const err = await res.json();
  7001. showToast('Error', err.message, 'error');
  7002. }
  7003. } catch (err) {
  7004. showToast('Error', err.message, 'error');
  7005. }
  7006. }
  7007. // IPSec Server Modal
  7008. function openIPSecServerModal() {
  7009. loadPPPServers();
  7010. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7011. }
  7012. function closeIPSecServerModal() {
  7013. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7014. }
  7015. async function submitSaveIPSecServer(e) {
  7016. e.preventDefault();
  7017. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7018. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7019. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7020. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7021. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7022. try {
  7023. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7024. method: 'POST',
  7025. headers: { 'Content-Type': 'application/json' },
  7026. body: JSON.stringify({
  7027. enabled,
  7028. preshared_key: psk,
  7029. pool_address: pool,
  7030. dns_servers: dns,
  7031. local_subnet: subnet
  7032. })
  7033. });
  7034. if (res.ok) {
  7035. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7036. closeIPSecServerModal();
  7037. loadPPPServers();
  7038. fetchData(false);
  7039. } else {
  7040. const err = await res.json();
  7041. showToast('Error', err.message, 'error');
  7042. }
  7043. } catch (err) {
  7044. showToast('Error', err.message, 'error');
  7045. }
  7046. }
  7047. // WireGuard Client Config Viewer
  7048. let currentWGClientConf = '';
  7049. async function openWGClientConfModal(iface, clientIP) {
  7050. try {
  7051. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7052. method: 'POST',
  7053. headers: { 'Content-Type': 'application/json' },
  7054. body: JSON.stringify({
  7055. interface: iface,
  7056. address: clientIP || '10.10.0.2/32',
  7057. dns: '1.1.1.1, 8.8.8.8'
  7058. })
  7059. });
  7060. if (res.ok) {
  7061. const data = await res.json();
  7062. currentWGClientConf = data.config;
  7063. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7064. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7065. } else {
  7066. const err = await res.json();
  7067. showToast('Error', err.message, 'error');
  7068. }
  7069. } catch (err) {
  7070. showToast('Error', err.message, 'error');
  7071. }
  7072. }
  7073. function closeWGClientConfModal() {
  7074. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7075. }
  7076. function copyWGClientConf() {
  7077. if (!currentWGClientConf) return;
  7078. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7079. }
  7080. function downloadWGClientConf() {
  7081. if (!currentWGClientConf) return;
  7082. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7083. const a = document.createElement('a');
  7084. a.href = URL.createObjectURL(blob);
  7085. a.download = 'wireguard-client.conf';
  7086. document.body.appendChild(a);
  7087. a.click();
  7088. document.body.removeChild(a);
  7089. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7090. }
  7091. // =========================================================================
  7092. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7093. // =========================================================================
  7094. state.activeDynSubTab = 'bgp-peers';
  7095. state.activeBgpSubTab = 'bgp-peers';
  7096. state.activeOspfTab = 'instances';
  7097. state.bgpInstance = null;
  7098. state.bgpPeers = [];
  7099. state.bgpNets = [];
  7100. state.bgpRoutes = [];
  7101. state.ospfInstance = null;
  7102. state.ospfInstances = [];
  7103. state.ospfAreas = [];
  7104. state.ospfAreaRanges = [];
  7105. state.ospfTemplates = [];
  7106. state.ospfLiveInterfaces = [];
  7107. state.ospfStaticNbrs = [];
  7108. state.ospfNeighbors = [];
  7109. state.ospfLSA = [];
  7110. state.ospfRoutes = [];
  7111. state.selectedOspfRow = {
  7112. instances: null,
  7113. areas: null,
  7114. 'area-ranges': null,
  7115. templates: null,
  7116. interfaces: null,
  7117. 'static-nbrs': null,
  7118. neighbors: null,
  7119. lsa: null,
  7120. };
  7121. state.ospfSort = {
  7122. instances: { col: 'name', asc: true },
  7123. areas: { col: 'name', asc: true },
  7124. ranges: { col: 'area', asc: true },
  7125. templates: { col: 'interfaces', asc: true },
  7126. live_ifaces: { col: 'interface', asc: true },
  7127. snbrs: { col: 'address', asc: true },
  7128. neighbors: { col: 'address', asc: true },
  7129. lsa: { col: 'instance', asc: true },
  7130. };
  7131. function switchBgpSubTab(subTab) {
  7132. state.activeBgpSubTab = subTab;
  7133. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7134. tabs.forEach(t => {
  7135. const el = document.getElementById(`dyn-subtab-${t}`);
  7136. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7137. if (el) el.classList.toggle('hidden', t !== subTab);
  7138. if (btn) {
  7139. if (t === subTab) {
  7140. 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';
  7141. } else {
  7142. 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';
  7143. }
  7144. }
  7145. });
  7146. }
  7147. function switchOspfTab(tabName) {
  7148. state.activeOspfTab = tabName;
  7149. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7150. tabs.forEach(t => {
  7151. const pane = document.getElementById(`ospf-pane-${t}`);
  7152. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7153. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7154. if (btn) {
  7155. if (t === tabName) {
  7156. 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';
  7157. } else {
  7158. 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';
  7159. }
  7160. }
  7161. });
  7162. }
  7163. function switchOspfSubTab(tab) {
  7164. // Legacy alias
  7165. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7166. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7167. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7168. else switchOspfTab('instances');
  7169. }
  7170. function switchDynSubTab(subTab) {
  7171. if (subTab.startsWith('bgp')) {
  7172. if (state.activeTab !== 'bgp') navigate('bgp');
  7173. switchBgpSubTab(subTab);
  7174. } else if (subTab.startsWith('ospf')) {
  7175. if (state.activeTab !== 'ospf') navigate('ospf');
  7176. switchOspfTab('instances');
  7177. }
  7178. }
  7179. async function loadDynamicRouting(showToastMsg = false) {
  7180. try {
  7181. const fetchSafeJson = async (url) => {
  7182. try {
  7183. const r = await fetch(url);
  7184. return r.ok ? await r.json() : null;
  7185. } catch (e) {
  7186. return null;
  7187. }
  7188. };
  7189. const [
  7190. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7191. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7192. selectRules, commLists, asLists
  7193. ] = await Promise.all([
  7194. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7195. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7196. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7197. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7198. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7199. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7200. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7201. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7202. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7203. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7204. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7205. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7206. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7207. fetchSafeJson(`${API_BASE}/routing/filters`),
  7208. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7209. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7210. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7211. ]);
  7212. if (sum) state.dynSummary = sum;
  7213. if (bgpInst) state.bgpInstance = bgpInst;
  7214. if (bgpPeers) state.bgpPeers = bgpPeers;
  7215. if (bgpNets) state.bgpNets = bgpNets;
  7216. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7217. if (ospfInsts) state.ospfInstances = ospfInsts;
  7218. if (ospfAreas) state.ospfAreas = ospfAreas;
  7219. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7220. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7221. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7222. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7223. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7224. if (ospfLsa) state.ospfLSA = ospfLsa;
  7225. if (filters) state.routingFilters = filters;
  7226. if (selectRules) state.routingSelectRules = selectRules;
  7227. if (commLists) state.routingCommunityLists = commLists;
  7228. if (asLists) state.routingASLists = asLists;
  7229. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7230. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7231. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7232. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7233. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7234. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7235. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7236. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7237. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7238. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7239. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7240. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7241. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7242. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7243. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7244. } catch (err) {
  7245. console.error('Failed to load dynamic routing:', err);
  7246. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7247. }
  7248. }
  7249. async function loadOspfAll() {
  7250. await loadDynamicRouting(true);
  7251. }
  7252. function renderBgpStatusPill() {
  7253. const pill = document.getElementById('bgp-live-status-pill');
  7254. if (!pill) return;
  7255. const inst = state.bgpInstance;
  7256. if (!inst || !inst.enabled) {
  7257. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7258. pill.innerText = 'BGP DISABLED';
  7259. } else if (inst.running) {
  7260. 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';
  7261. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7262. } else {
  7263. 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';
  7264. pill.innerText = 'BGP STARTING...';
  7265. }
  7266. }
  7267. function renderBgpPeers() {
  7268. const tbody = document.getElementById('bgp-peers-table-body');
  7269. if (!tbody) return;
  7270. const empty = document.getElementById('bgp-peers-empty');
  7271. const countBadge = document.getElementById('bgp-peers-count-badge');
  7272. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7273. const peers = state.bgpPeers || [];
  7274. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7275. if (navBadge) navBadge.innerText = peers.length;
  7276. if (peers.length === 0) {
  7277. tbody.innerHTML = '';
  7278. if (empty) empty.classList.remove('hidden');
  7279. return;
  7280. }
  7281. if (empty) empty.classList.add('hidden');
  7282. tbody.innerHTML = peers.map(p => {
  7283. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7284. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7285. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7286. let stateBadge = '';
  7287. if (p.disabled) {
  7288. 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>';
  7289. } else if (p.state === 'Established') {
  7290. 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>';
  7291. } else if (p.state === 'Connect' || p.state === 'Active') {
  7292. 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>`;
  7293. } else {
  7294. 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>`;
  7295. }
  7296. return `
  7297. <tr class="hover:bg-slate-800/40 transition">
  7298. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7299. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7300. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7301. <td class="py-2.5 px-3">
  7302. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7303. ${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>`}
  7304. </td>
  7305. <td class="py-2.5 px-3">${stateBadge}</td>
  7306. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7307. <td class="py-2.5 px-3 text-slate-300">
  7308. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7309. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7310. </td>
  7311. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7312. ${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> ` : ''}
  7313. ${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>` : ''}
  7314. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7315. </td>
  7316. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7317. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7318. <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'}">
  7319. ${p.disabled ? 'Enable' : 'Disable'}
  7320. </button>
  7321. <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">
  7322. Edit
  7323. </button>
  7324. <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">
  7325. Delete
  7326. </button>
  7327. </td>
  7328. </tr>
  7329. `;
  7330. }).join('');
  7331. }
  7332. function renderBgpNetworks() {
  7333. const tbody = document.getElementById('bgp-nets-table-body');
  7334. if (!tbody) return;
  7335. const empty = document.getElementById('bgp-nets-empty');
  7336. const countBadge = document.getElementById('bgp-nets-count-badge');
  7337. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7338. const nets = state.bgpNets || [];
  7339. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7340. if (navBadge) navBadge.innerText = nets.length;
  7341. if (nets.length === 0) {
  7342. tbody.innerHTML = '';
  7343. if (empty) empty.classList.remove('hidden');
  7344. return;
  7345. }
  7346. if (empty) empty.classList.add('hidden');
  7347. tbody.innerHTML = nets.map(n => `
  7348. <tr class="hover:bg-slate-800/40 transition">
  7349. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7350. <td class="py-2.5 px-3">
  7351. ${n.disabled
  7352. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7353. : '<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>'}
  7354. </td>
  7355. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7356. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7357. <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">
  7358. Delete
  7359. </button>
  7360. </td>
  7361. </tr>
  7362. `).join('');
  7363. }
  7364. function renderBgpRoutes() {
  7365. const tbody = document.getElementById('bgp-routes-table-body');
  7366. if (!tbody) return;
  7367. const empty = document.getElementById('bgp-routes-empty');
  7368. const countBadge = document.getElementById('bgp-routes-count-badge');
  7369. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7370. const routes = state.bgpRoutes || [];
  7371. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7372. if (navBadge) navBadge.innerText = routes.length;
  7373. if (routes.length === 0) {
  7374. tbody.innerHTML = '';
  7375. if (empty) empty.classList.remove('hidden');
  7376. return;
  7377. }
  7378. if (empty) empty.classList.add('hidden');
  7379. tbody.innerHTML = routes.map(r => `
  7380. <tr class="hover:bg-slate-800/40 transition">
  7381. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7382. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7383. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7384. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7385. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7386. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7387. </tr>
  7388. `).join('');
  7389. }
  7390. // =========================================================================
  7391. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7392. // =========================================================================
  7393. function sortOspfTable(tab, col) {
  7394. if (!state.ospfSort) state.ospfSort = {};
  7395. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7396. if (state.ospfSort[tab].col === col) {
  7397. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7398. } else {
  7399. state.ospfSort[tab].col = col;
  7400. state.ospfSort[tab].asc = true;
  7401. }
  7402. const asc = state.ospfSort[tab].asc;
  7403. let list = [];
  7404. if (tab === 'instances') list = state.ospfInstances || [];
  7405. else if (tab === 'areas') list = state.ospfAreas || [];
  7406. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7407. else if (tab === 'templates') list = state.ospfTemplates || [];
  7408. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7409. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7410. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7411. else if (tab === 'lsa') list = state.ospfLSA || [];
  7412. list.sort((a, b) => {
  7413. let valA = a[col] ?? '';
  7414. let valB = b[col] ?? '';
  7415. if (typeof valA === 'number' && typeof valB === 'number') {
  7416. return asc ? valA - valB : valB - valA;
  7417. }
  7418. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7419. });
  7420. if (tab === 'instances') renderOspfInstances();
  7421. else if (tab === 'areas') renderOspfAreas();
  7422. else if (tab === 'ranges') renderOspfAreaRanges();
  7423. else if (tab === 'templates') renderOspfTemplates();
  7424. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7425. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7426. else if (tab === 'neighbors') renderOspfNeighbors();
  7427. else if (tab === 'lsa') renderOspfLSA();
  7428. }
  7429. function selectOspfRow(tab, id) {
  7430. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7431. state.selectedOspfRow[tab] = id;
  7432. if (tab === 'instances') {
  7433. renderOspfInstances();
  7434. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7435. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7436. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7437. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7438. if (btnEn) btnEn.disabled = false;
  7439. if (btnDis) btnDis.disabled = false;
  7440. if (btnRem) btnRem.disabled = false;
  7441. if (btnCom) btnCom.disabled = false;
  7442. } else if (tab === 'areas') {
  7443. renderOspfAreas();
  7444. const btnEn = document.getElementById('btn-ospf-area-enable');
  7445. const btnDis = document.getElementById('btn-ospf-area-disable');
  7446. const btnRem = document.getElementById('btn-ospf-area-remove');
  7447. const btnCom = document.getElementById('btn-ospf-area-comment');
  7448. if (btnEn) btnEn.disabled = false;
  7449. if (btnDis) btnDis.disabled = false;
  7450. if (btnRem) btnRem.disabled = false;
  7451. if (btnCom) btnCom.disabled = false;
  7452. } else if (tab === 'ranges') {
  7453. renderOspfAreaRanges();
  7454. const btnEn = document.getElementById('btn-ospf-range-enable');
  7455. const btnDis = document.getElementById('btn-ospf-range-disable');
  7456. const btnRem = document.getElementById('btn-ospf-range-remove');
  7457. const btnCom = document.getElementById('btn-ospf-range-comment');
  7458. if (btnEn) btnEn.disabled = false;
  7459. if (btnDis) btnDis.disabled = false;
  7460. if (btnRem) btnRem.disabled = false;
  7461. if (btnCom) btnCom.disabled = false;
  7462. } else if (tab === 'templates') {
  7463. renderOspfTemplates();
  7464. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7465. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7466. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7467. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7468. if (btnEn) btnEn.disabled = false;
  7469. if (btnDis) btnDis.disabled = false;
  7470. if (btnRem) btnRem.disabled = false;
  7471. if (btnCom) btnCom.disabled = false;
  7472. } else if (tab === 'snbrs') {
  7473. renderOspfStaticNbrs();
  7474. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7475. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7476. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7477. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7478. if (btnEn) btnEn.disabled = false;
  7479. if (btnDis) btnDis.disabled = false;
  7480. if (btnRem) btnRem.disabled = false;
  7481. if (btnCom) btnCom.disabled = false;
  7482. }
  7483. }
  7484. // TAB 1: INSTANCES
  7485. function renderOspfInstances() {
  7486. const tbody = document.getElementById('ospf-instances-table-body');
  7487. if (!tbody) return;
  7488. const countEl = document.getElementById('ospf-instances-footer-count');
  7489. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7490. let list = state.ospfInstances || [];
  7491. if (filter) {
  7492. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7493. }
  7494. if (countEl) countEl.innerText = list.length;
  7495. const selId = state.selectedOspfRow?.instances;
  7496. tbody.innerHTML = list.map((inst, idx) => {
  7497. const isSel = inst.id === selId;
  7498. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7499. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7500. return `
  7501. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7502. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7503. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7504. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7505. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7506. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7507. </td>
  7508. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7509. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7510. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7511. </tr>
  7512. `;
  7513. }).join('');
  7514. }
  7515. // TAB 2: AREAS
  7516. function renderOspfAreas() {
  7517. const tbody = document.getElementById('ospf-areas-table-body');
  7518. if (!tbody) return;
  7519. const countEl = document.getElementById('ospf-areas-footer-count');
  7520. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7521. let list = state.ospfAreas || [];
  7522. if (filter) {
  7523. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7524. }
  7525. if (countEl) countEl.innerText = list.length;
  7526. const selId = state.selectedOspfRow?.areas;
  7527. tbody.innerHTML = list.map((a, idx) => {
  7528. const isSel = a.id === selId;
  7529. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7530. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7531. return `
  7532. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7533. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7534. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7535. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7536. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7537. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7538. </td>
  7539. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7540. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7541. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7542. </tr>
  7543. `;
  7544. }).join('');
  7545. }
  7546. // TAB 3: AREA RANGES
  7547. function renderOspfAreaRanges() {
  7548. const tbody = document.getElementById('ospf-ranges-table-body');
  7549. if (!tbody) return;
  7550. const countEl = document.getElementById('ospf-ranges-footer-count');
  7551. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7552. let list = state.ospfAreaRanges || [];
  7553. if (filter) {
  7554. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7555. }
  7556. if (countEl) countEl.innerText = list.length;
  7557. const selId = state.selectedOspfRow?.['area-ranges'];
  7558. tbody.innerHTML = list.map((r, idx) => {
  7559. const isSel = r.id === selId;
  7560. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7561. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7562. return `
  7563. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7564. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7565. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7566. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7567. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7568. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7569. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7570. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7571. </tr>
  7572. `;
  7573. }).join('');
  7574. }
  7575. // TAB 4: INTERFACE TEMPLATES
  7576. function renderOspfTemplates() {
  7577. const tbody = document.getElementById('ospf-templates-table-body');
  7578. if (!tbody) return;
  7579. const countEl = document.getElementById('ospf-templates-footer-count');
  7580. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7581. let list = state.ospfTemplates || [];
  7582. if (filter) {
  7583. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7584. }
  7585. if (countEl) countEl.innerText = list.length;
  7586. const selId = state.selectedOspfRow?.templates;
  7587. tbody.innerHTML = list.map((t, idx) => {
  7588. const isSel = t.id === selId;
  7589. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7590. const ifaces = t.interfaces || t.interface || 'all';
  7591. const nets = t.networks || t.network || '';
  7592. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7593. return `
  7594. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7595. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7596. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7597. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7598. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7599. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7600. </td>
  7601. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7602. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7603. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7604. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7605. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7606. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7607. </tr>
  7608. `;
  7609. }).join('');
  7610. }
  7611. // TAB 5: LIVE INTERFACES
  7612. function renderOspfLiveInterfaces() {
  7613. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7614. if (!tbody) return;
  7615. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7616. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7617. let list = state.ospfLiveInterfaces || [];
  7618. if (filter) {
  7619. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7620. }
  7621. if (countEl) countEl.innerText = list.length;
  7622. tbody.innerHTML = list.map(i => `
  7623. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7624. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7625. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7626. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7627. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7628. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7629. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7630. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7631. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7632. </tr>
  7633. `).join('');
  7634. }
  7635. // TAB 6: STATIC NEIGHBORS
  7636. function renderOspfStaticNbrs() {
  7637. const tbody = document.getElementById('ospf-snbrs-table-body');
  7638. if (!tbody) return;
  7639. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7640. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7641. let list = state.ospfStaticNbrs || [];
  7642. if (filter) {
  7643. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7644. }
  7645. if (countEl) countEl.innerText = list.length;
  7646. const selId = state.selectedOspfRow?.['static-nbrs'];
  7647. tbody.innerHTML = list.map((n, idx) => {
  7648. const isSel = n.id === selId;
  7649. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7650. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7651. return `
  7652. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7653. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7654. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7655. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7656. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7657. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7658. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7659. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7660. </tr>
  7661. `;
  7662. }).join('');
  7663. }
  7664. // TAB 7: LIVE NEIGHBORS
  7665. function renderOspfNeighbors() {
  7666. const tbody = document.getElementById('ospf-neighbors-table-body');
  7667. if (!tbody) return;
  7668. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7669. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7670. let list = state.ospfNeighbors || [];
  7671. if (filter) {
  7672. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7673. }
  7674. if (countEl) countEl.innerText = list.length;
  7675. tbody.innerHTML = list.map(n => `
  7676. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7677. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7678. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7679. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7680. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7681. </td>
  7682. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7683. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7684. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7685. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7686. </tr>
  7687. `).join('');
  7688. }
  7689. // TAB 8: LINK-STATE DATABASE (LSA)
  7690. function renderOspfLSA() {
  7691. const tbody = document.getElementById('ospf-lsa-table-body');
  7692. if (!tbody) return;
  7693. const countEl = document.getElementById('ospf-lsa-footer-count');
  7694. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7695. let list = state.ospfLSA || [];
  7696. if (filter) {
  7697. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7698. }
  7699. if (countEl) countEl.innerText = list.length;
  7700. tbody.innerHTML = list.map(l => `
  7701. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7702. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7703. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7704. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7705. </td>
  7706. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7707. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7708. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7709. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7710. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7711. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7712. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7713. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7714. </tr>
  7715. `).join('');
  7716. }
  7717. function renderOspfStatusPill() {
  7718. // Maintained for backward compatibility
  7719. const pill = document.getElementById('ospf-live-status-pill');
  7720. if (!pill) return;
  7721. 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';
  7722. pill.innerText = 'OSPF ACTIVE';
  7723. }
  7724. function renderOspfInterfaces() {
  7725. renderOspfTemplates();
  7726. }
  7727. function renderOspfRoutes() {
  7728. // Routes retained in background
  7729. }
  7730. // BGP Modals & Actions
  7731. function openBgpInstanceModal() {
  7732. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7733. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7734. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7735. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7736. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7737. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7738. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7739. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7740. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7741. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7742. }
  7743. function closeBgpInstanceModal() {
  7744. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7745. }
  7746. async function submitBgpInstance(e) {
  7747. e.preventDefault();
  7748. const payload = {
  7749. enabled: document.getElementById('modal-bgp-enabled').checked,
  7750. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7751. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7752. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7753. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7754. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7755. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7756. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7757. };
  7758. try {
  7759. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7760. method: 'POST',
  7761. headers: { 'Content-Type': 'application/json' },
  7762. body: JSON.stringify(payload)
  7763. });
  7764. if (res.ok) {
  7765. closeBgpInstanceModal();
  7766. showToast('Success', 'BGP instance configuration updated', 'success');
  7767. loadDynamicRouting();
  7768. } else {
  7769. const err = await res.json();
  7770. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7771. }
  7772. } catch (err) {
  7773. showToast('Error', err.message, 'error');
  7774. }
  7775. }
  7776. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7777. function switchBgpPeerModalTab(tab) {
  7778. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7779. tabs.forEach(t => {
  7780. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7781. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7782. if (t === tab) {
  7783. if (pane) pane.classList.remove('hidden');
  7784. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7785. } else {
  7786. if (pane) pane.classList.add('hidden');
  7787. 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';
  7788. }
  7789. });
  7790. }
  7791. function addOutputNetworkRow(val = '') {
  7792. const container = document.getElementById('modal-bgp-output-networks-container');
  7793. if (!container) return;
  7794. const row = document.createElement('div');
  7795. row.className = 'flex items-center gap-2 output-net-row';
  7796. row.innerHTML = `
  7797. <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">
  7798. <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>
  7799. `;
  7800. container.appendChild(row);
  7801. }
  7802. function parseBgpTime(val) {
  7803. if (!val) return 0;
  7804. val = String(val).trim();
  7805. if (val.includes(':')) {
  7806. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7807. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7808. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7809. }
  7810. return parseInt(val, 10) || 0;
  7811. }
  7812. function formatBgpTime(secs) {
  7813. if (!secs || secs <= 0) return '00:00:00';
  7814. const h = Math.floor(secs / 3600);
  7815. const m = Math.floor((secs % 3600) / 60);
  7816. const s = secs % 60;
  7817. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7818. }
  7819. function populateBgpRoutingTables() {
  7820. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7821. if (!sel) return;
  7822. const cur = sel.value || 'main';
  7823. sel.innerHTML = '<option value="main">main</option>';
  7824. (state.routingTables || []).forEach(t => {
  7825. if (t.name !== 'main') {
  7826. const opt = document.createElement('option');
  7827. opt.value = t.name;
  7828. opt.innerText = t.name;
  7829. sel.appendChild(opt);
  7830. }
  7831. });
  7832. sel.value = cur;
  7833. }
  7834. function openAddBgpPeerModal() {
  7835. document.getElementById('bgp-peer-form').reset();
  7836. document.getElementById('modal-bgp-peer-id').value = '';
  7837. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7838. // General Tab
  7839. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7840. document.getElementById('modal-bgp-peer-comment').value = '';
  7841. document.getElementById('modal-bgp-peer-name').value = '';
  7842. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7843. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7844. document.getElementById('modal-bgp-peer-local-as').value = '';
  7845. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7846. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7847. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7848. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7849. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7850. document.getElementById('modal-bgp-peer-router-id').value = '';
  7851. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7852. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7853. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7854. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7855. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7856. document.getElementById('modal-bgp-peer-local-port').value = '';
  7857. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7858. document.getElementById('modal-bgp-peer-password').value = '';
  7859. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7860. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7861. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7862. document.getElementById('modal-bgp-peer-connect').checked = true;
  7863. document.getElementById('modal-bgp-peer-listen').checked = true;
  7864. // Extra Tab
  7865. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7866. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7867. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7868. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7869. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7870. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7871. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7872. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7873. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7874. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7875. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7876. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7877. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7878. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7879. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7880. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7881. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7882. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7883. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7884. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7885. // Attributes Tab
  7886. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7887. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7888. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7889. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7890. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7891. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7892. // Filter Tab
  7893. populateFilterChainsDatalist();
  7894. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7895. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7896. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7897. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7898. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7899. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7900. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7901. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7902. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7903. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7904. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7905. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7906. populateBgpRoutingTables();
  7907. const container = document.getElementById('modal-bgp-output-networks-container');
  7908. if (container) {
  7909. container.innerHTML = '';
  7910. addOutputNetworkRow('');
  7911. }
  7912. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7913. if (removeBtn) removeBtn.classList.add('hidden');
  7914. switchBgpPeerModalTab('general');
  7915. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7916. }
  7917. function populateFilterChainsDatalist() {
  7918. const dl = document.getElementById('filter-chains-list');
  7919. if (!dl) return;
  7920. const chains = new Set();
  7921. (state.routingFilters || []).forEach(f => {
  7922. if (f.chain) chains.add(f.chain);
  7923. });
  7924. if (chains.size === 0) {
  7925. chains.add('awmn');
  7926. chains.add('bgp-in');
  7927. chains.add('bgp-out');
  7928. }
  7929. dl.innerHTML = '';
  7930. chains.forEach(c => {
  7931. const opt = document.createElement('option');
  7932. opt.value = c;
  7933. dl.appendChild(opt);
  7934. });
  7935. }
  7936. function openEditBgpPeerModal(id) {
  7937. const p = (state.bgpPeers || []).find(item => item.id === id);
  7938. if (!p) return;
  7939. populateBgpRoutingTables();
  7940. populateFilterChainsDatalist();
  7941. document.getElementById('modal-bgp-peer-id').value = p.id;
  7942. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7943. // General Tab
  7944. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7945. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7946. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7947. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7948. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7949. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7950. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7951. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7952. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7953. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7954. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7955. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7956. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7957. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7958. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7959. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7960. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7961. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7962. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7963. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7964. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7965. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7966. // Extra Tab
  7967. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7968. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7969. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7970. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7971. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7972. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7973. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7974. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7975. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7976. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7977. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7978. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7979. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7980. 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;
  7981. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7982. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7983. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7984. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7985. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7986. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7987. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7988. // Attributes Tab
  7989. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7990. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7991. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7992. 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;
  7993. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7994. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7995. // Filter Tab
  7996. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7997. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7998. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7999. 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 || '';
  8000. 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 || '';
  8001. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8002. 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 || '';
  8003. 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 || '';
  8004. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8005. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8006. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8007. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8008. // Output Networks
  8009. const container = document.getElementById('modal-bgp-output-networks-container');
  8010. if (container) {
  8011. container.innerHTML = '';
  8012. if (p.output_networks && p.output_networks.length > 0) {
  8013. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8014. } else {
  8015. addOutputNetworkRow('');
  8016. }
  8017. }
  8018. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8019. if (removeBtn) removeBtn.classList.remove('hidden');
  8020. switchBgpPeerModalTab('general');
  8021. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8022. }
  8023. function copyCurrentBgpPeer() {
  8024. document.getElementById('modal-bgp-peer-id').value = '';
  8025. const nameEl = document.getElementById('modal-bgp-peer-name');
  8026. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8027. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8028. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8029. if (removeBtn) removeBtn.classList.add('hidden');
  8030. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8031. }
  8032. function removeCurrentBgpPeer() {
  8033. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8034. if (!id) return;
  8035. deleteBgpPeer(id);
  8036. closeBgpPeerModal();
  8037. }
  8038. function closeBgpPeerModal() {
  8039. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8040. }
  8041. function getBgpPeerFormData() {
  8042. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8043. const outputNetworks = [];
  8044. netInputs.forEach(inp => {
  8045. const v = inp.value.trim();
  8046. if (v) outputNetworks.push(v);
  8047. });
  8048. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8049. return {
  8050. id: document.getElementById('modal-bgp-peer-id').value,
  8051. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8052. enabled: enabled,
  8053. disabled: !enabled,
  8054. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8055. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8056. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8057. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8058. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8059. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8060. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8061. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8062. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8063. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8064. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8065. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8066. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8067. password: document.getElementById('modal-bgp-peer-password').value,
  8068. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8069. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8070. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8071. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8072. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8073. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8074. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8075. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8076. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8077. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8078. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8079. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8080. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8081. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8082. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8083. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8084. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8085. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8086. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8087. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8088. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8089. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8090. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8091. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8092. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8093. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8094. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8095. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8096. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8097. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8098. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8099. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8100. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8101. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8102. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8103. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8104. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8105. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8106. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8107. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8108. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8109. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8110. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8111. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8112. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8113. output_networks: outputNetworks
  8114. };
  8115. }
  8116. async function submitBgpPeer(e) {
  8117. if (e) e.preventDefault();
  8118. const payload = getBgpPeerFormData();
  8119. try {
  8120. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8121. method: 'POST',
  8122. headers: { 'Content-Type': 'application/json' },
  8123. body: JSON.stringify(payload)
  8124. });
  8125. if (res.ok) {
  8126. closeBgpPeerModal();
  8127. showToast('Success', 'BGP Connection saved', 'success');
  8128. loadDynamicRouting();
  8129. } else {
  8130. const err = await res.json();
  8131. showToast('Error', err.error || 'Failed to save peer', 'error');
  8132. }
  8133. } catch (err) {
  8134. showToast('Error', err.message, 'error');
  8135. }
  8136. }
  8137. async function applyBgpPeerModal(e) {
  8138. if (e) e.preventDefault();
  8139. const payload = getBgpPeerFormData();
  8140. try {
  8141. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8142. method: 'POST',
  8143. headers: { 'Content-Type': 'application/json' },
  8144. body: JSON.stringify(payload)
  8145. });
  8146. if (res.ok) {
  8147. const data = await res.json();
  8148. if (data.peer && data.peer.id) {
  8149. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8150. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8151. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8152. }
  8153. showToast('Applied', 'BGP Connection applied', 'success');
  8154. loadDynamicRouting();
  8155. } else {
  8156. const err = await res.json();
  8157. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8158. }
  8159. } catch (err) {
  8160. showToast('Error', err.message, 'error');
  8161. }
  8162. }
  8163. async function deleteBgpPeer(id) {
  8164. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8165. try {
  8166. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8167. if (res.ok) {
  8168. showToast('Deleted', 'BGP peer removed', 'success');
  8169. loadDynamicRouting();
  8170. }
  8171. } catch (err) {
  8172. showToast('Error', err.message, 'error');
  8173. }
  8174. }
  8175. async function toggleBgpPeerState(id, disabled) {
  8176. try {
  8177. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8178. method: 'POST',
  8179. headers: { 'Content-Type': 'application/json' },
  8180. body: JSON.stringify({ disabled })
  8181. });
  8182. if (res.ok) {
  8183. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8184. loadDynamicRouting();
  8185. }
  8186. } catch (err) {
  8187. showToast('Error', err.message, 'error');
  8188. }
  8189. }
  8190. function openAddBgpNetworkModal() {
  8191. document.getElementById('bgp-network-form').reset();
  8192. document.getElementById('modal-bgp-net-id').value = '';
  8193. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8194. }
  8195. function closeBgpNetworkModal() {
  8196. document.getElementById('bgp-network-modal').classList.add('hidden');
  8197. }
  8198. async function submitBgpNetwork(e) {
  8199. e.preventDefault();
  8200. const payload = {
  8201. id: document.getElementById('modal-bgp-net-id').value,
  8202. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8203. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8204. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8205. };
  8206. try {
  8207. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8208. method: 'POST',
  8209. headers: { 'Content-Type': 'application/json' },
  8210. body: JSON.stringify(payload)
  8211. });
  8212. if (res.ok) {
  8213. closeBgpNetworkModal();
  8214. showToast('Success', 'BGP network advertisement saved', 'success');
  8215. loadDynamicRouting();
  8216. } else {
  8217. const err = await res.json();
  8218. showToast('Error', err.error || 'Failed to save network', 'error');
  8219. }
  8220. } catch (err) {
  8221. showToast('Error', err.message, 'error');
  8222. }
  8223. }
  8224. async function deleteBgpNetwork(id) {
  8225. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8226. try {
  8227. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8228. if (res.ok) {
  8229. showToast('Deleted', 'Network advertisement removed', 'success');
  8230. loadDynamicRouting();
  8231. }
  8232. } catch (err) {
  8233. showToast('Error', err.message, 'error');
  8234. }
  8235. }
  8236. // =========================================================================
  8237. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8238. // =========================================================================
  8239. // --- 1. OSPF INSTANCE ---
  8240. function openOspfInstanceModal(id = null) {
  8241. const isEdit = !!id;
  8242. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8243. id: '',
  8244. name: 'Default',
  8245. version: 2,
  8246. vrf: 'main',
  8247. router_id: '192.168.131.56',
  8248. routing_table: 'main',
  8249. enabled: true,
  8250. redistribute_connected: false,
  8251. redistribute_static: true,
  8252. redistribute_bgp: false,
  8253. comment: ''
  8254. };
  8255. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8256. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8257. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8258. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8259. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8260. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8261. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8262. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8263. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8264. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8265. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8266. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8267. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8268. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8269. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8270. }
  8271. function openEditOspfInstanceModal(id) {
  8272. openOspfInstanceModal(id);
  8273. }
  8274. function closeOspfInstanceModal() {
  8275. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8276. }
  8277. async function submitOspfInstance(e) {
  8278. if (e) e.preventDefault();
  8279. const payload = {
  8280. id: document.getElementById('modal-ospf-inst-id').value,
  8281. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8282. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8283. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8284. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8285. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8286. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8287. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8288. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8289. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8290. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8291. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8292. };
  8293. try {
  8294. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8295. method: 'POST',
  8296. headers: { 'Content-Type': 'application/json' },
  8297. body: JSON.stringify(payload)
  8298. });
  8299. if (res.ok) {
  8300. closeOspfInstanceModal();
  8301. showToast('Saved', 'OSPF instance updated', 'success');
  8302. loadDynamicRouting();
  8303. } else {
  8304. const err = await res.json();
  8305. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8306. }
  8307. } catch (err) {
  8308. showToast('Error', err.message, 'error');
  8309. }
  8310. }
  8311. function applyOspfInstanceForm() {
  8312. submitOspfInstance(null);
  8313. }
  8314. function copyOspfInstance() {
  8315. document.getElementById('modal-ospf-inst-id').value = '';
  8316. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8317. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8318. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8319. }
  8320. async function deleteCurrentOspfInstance() {
  8321. const id = document.getElementById('modal-ospf-inst-id').value;
  8322. if (!id) return;
  8323. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8324. try {
  8325. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8326. if (res.ok) {
  8327. closeOspfInstanceModal();
  8328. showToast('Removed', 'OSPF instance deleted', 'success');
  8329. loadDynamicRouting();
  8330. }
  8331. } catch (err) {
  8332. showToast('Error', err.message, 'error');
  8333. }
  8334. }
  8335. async function enableSelectedOspfInstance() {
  8336. const id = state.selectedOspfRow?.instances;
  8337. if (!id) return;
  8338. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8339. method: 'POST',
  8340. headers: { 'Content-Type': 'application/json' },
  8341. body: JSON.stringify({ disabled: false })
  8342. });
  8343. loadDynamicRouting();
  8344. }
  8345. async function disableSelectedOspfInstance() {
  8346. const id = state.selectedOspfRow?.instances;
  8347. if (!id) return;
  8348. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8349. method: 'POST',
  8350. headers: { 'Content-Type': 'application/json' },
  8351. body: JSON.stringify({ disabled: true })
  8352. });
  8353. loadDynamicRouting();
  8354. }
  8355. async function removeSelectedOspfInstance() {
  8356. const id = state.selectedOspfRow?.instances;
  8357. if (!id) return;
  8358. if (!confirm('Delete selected OSPF instance?')) return;
  8359. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8360. loadDynamicRouting();
  8361. }
  8362. async function promptCommentOspfInstance() {
  8363. const id = state.selectedOspfRow?.instances;
  8364. if (!id) return;
  8365. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8366. if (!inst) return;
  8367. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8368. if (comment === null) return;
  8369. inst.comment = comment;
  8370. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8371. method: 'POST',
  8372. headers: { 'Content-Type': 'application/json' },
  8373. body: JSON.stringify(inst)
  8374. });
  8375. loadDynamicRouting();
  8376. }
  8377. // --- 2. OSPF AREA ---
  8378. function populateOspfAreaDropdowns() {
  8379. const instSelect = document.getElementById('modal-ospf-area-instance');
  8380. if (instSelect) {
  8381. const cur = instSelect.value;
  8382. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8383. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8384. if (cur) instSelect.value = cur;
  8385. }
  8386. }
  8387. function openOspfAreaModal(id = null) {
  8388. const isEdit = !!id;
  8389. populateOspfAreaDropdowns();
  8390. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8391. id: '',
  8392. name: 'Default',
  8393. instance: 'Default',
  8394. area_id: '0.0.0.0',
  8395. area_type: 'default',
  8396. default_cost: 1,
  8397. no_summaries: false,
  8398. disabled: false,
  8399. comment: ''
  8400. };
  8401. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8402. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8403. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8404. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8405. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8406. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8407. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8408. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8409. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8410. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8411. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8412. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8413. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8414. }
  8415. function openEditOspfAreaModal(id) {
  8416. openOspfAreaModal(id);
  8417. }
  8418. function closeOspfAreaModal() {
  8419. document.getElementById('ospf-area-modal').classList.add('hidden');
  8420. }
  8421. async function submitOspfArea(e) {
  8422. if (e) e.preventDefault();
  8423. const payload = {
  8424. id: document.getElementById('modal-ospf-area-id').value,
  8425. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8426. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8427. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8428. area_type: document.getElementById('modal-ospf-area-type').value,
  8429. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8430. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8431. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8432. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8433. };
  8434. try {
  8435. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8436. method: 'POST',
  8437. headers: { 'Content-Type': 'application/json' },
  8438. body: JSON.stringify(payload)
  8439. });
  8440. if (res.ok) {
  8441. closeOspfAreaModal();
  8442. showToast('Saved', 'OSPF area saved', 'success');
  8443. loadDynamicRouting();
  8444. } else {
  8445. const err = await res.json();
  8446. showToast('Error', err.error || 'Failed to save area', 'error');
  8447. }
  8448. } catch (err) {
  8449. showToast('Error', err.message, 'error');
  8450. }
  8451. }
  8452. function applyOspfAreaForm() {
  8453. submitOspfArea(null);
  8454. }
  8455. function copyOspfArea() {
  8456. document.getElementById('modal-ospf-area-id').value = '';
  8457. document.getElementById('modal-ospf-area-name').value += '-copy';
  8458. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8459. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8460. }
  8461. async function deleteCurrentOspfArea() {
  8462. const id = document.getElementById('modal-ospf-area-id').value;
  8463. if (!id) return;
  8464. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8465. try {
  8466. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8467. if (res.ok) {
  8468. closeOspfAreaModal();
  8469. showToast('Removed', 'OSPF area deleted', 'success');
  8470. loadDynamicRouting();
  8471. }
  8472. } catch (err) {
  8473. showToast('Error', err.message, 'error');
  8474. }
  8475. }
  8476. async function enableSelectedOspfArea() {
  8477. const id = state.selectedOspfRow?.areas;
  8478. if (!id) return;
  8479. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8480. method: 'POST',
  8481. headers: { 'Content-Type': 'application/json' },
  8482. body: JSON.stringify({ disabled: false })
  8483. });
  8484. loadDynamicRouting();
  8485. }
  8486. async function disableSelectedOspfArea() {
  8487. const id = state.selectedOspfRow?.areas;
  8488. if (!id) return;
  8489. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8490. method: 'POST',
  8491. headers: { 'Content-Type': 'application/json' },
  8492. body: JSON.stringify({ disabled: true })
  8493. });
  8494. loadDynamicRouting();
  8495. }
  8496. async function removeSelectedOspfArea() {
  8497. const id = state.selectedOspfRow?.areas;
  8498. if (!id) return;
  8499. if (!confirm('Delete selected OSPF area?')) return;
  8500. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8501. loadDynamicRouting();
  8502. }
  8503. async function promptCommentOspfArea() {
  8504. const id = state.selectedOspfRow?.areas;
  8505. if (!id) return;
  8506. const area = (state.ospfAreas || []).find(a => a.id === id);
  8507. if (!area) return;
  8508. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8509. if (comment === null) return;
  8510. area.comment = comment;
  8511. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8512. method: 'POST',
  8513. headers: { 'Content-Type': 'application/json' },
  8514. body: JSON.stringify(area)
  8515. });
  8516. loadDynamicRouting();
  8517. }
  8518. // --- 3. OSPF AREA RANGE ---
  8519. function populateAreaRangeDropdowns() {
  8520. const select = document.getElementById('modal-ospf-range-area');
  8521. if (select) {
  8522. const cur = select.value;
  8523. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8524. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8525. if (cur) select.value = cur;
  8526. }
  8527. }
  8528. function openOspfAreaRangeModal(id = null) {
  8529. const isEdit = !!id;
  8530. populateAreaRangeDropdowns();
  8531. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8532. id: '',
  8533. area: 'Default',
  8534. prefix: '',
  8535. cost: 1,
  8536. advertise: true,
  8537. disabled: false,
  8538. comment: ''
  8539. };
  8540. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8541. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8542. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8543. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8544. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8545. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8546. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8547. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8548. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8549. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8550. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8551. }
  8552. function openEditOspfAreaRangeModal(id) {
  8553. openOspfAreaRangeModal(id);
  8554. }
  8555. function closeOspfAreaRangeModal() {
  8556. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8557. }
  8558. async function submitOspfAreaRange(e) {
  8559. if (e) e.preventDefault();
  8560. const payload = {
  8561. id: document.getElementById('modal-ospf-range-id').value,
  8562. area: document.getElementById('modal-ospf-range-area').value,
  8563. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8564. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8565. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8566. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8567. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8568. };
  8569. try {
  8570. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8571. method: 'POST',
  8572. headers: { 'Content-Type': 'application/json' },
  8573. body: JSON.stringify(payload)
  8574. });
  8575. if (res.ok) {
  8576. closeOspfAreaRangeModal();
  8577. showToast('Saved', 'Area range saved', 'success');
  8578. loadDynamicRouting();
  8579. } else {
  8580. const err = await res.json();
  8581. showToast('Error', err.error || 'Failed to save area range', 'error');
  8582. }
  8583. } catch (err) {
  8584. showToast('Error', err.message, 'error');
  8585. }
  8586. }
  8587. function applyOspfAreaRangeForm() {
  8588. submitOspfAreaRange(null);
  8589. }
  8590. async function deleteCurrentOspfAreaRange() {
  8591. const id = document.getElementById('modal-ospf-range-id').value;
  8592. if (!id) return;
  8593. if (!confirm('Delete this area range?')) return;
  8594. try {
  8595. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8596. closeOspfAreaRangeModal();
  8597. showToast('Removed', 'Area range removed', 'success');
  8598. loadDynamicRouting();
  8599. } catch (err) {
  8600. showToast('Error', err.message, 'error');
  8601. }
  8602. }
  8603. async function enableSelectedOspfAreaRange() {
  8604. const id = state.selectedOspfRow?.['area-ranges'];
  8605. if (!id) return;
  8606. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8607. if (!r) return;
  8608. r.disabled = false;
  8609. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8610. loadDynamicRouting();
  8611. }
  8612. async function disableSelectedOspfAreaRange() {
  8613. const id = state.selectedOspfRow?.['area-ranges'];
  8614. if (!id) return;
  8615. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8616. if (!r) return;
  8617. r.disabled = true;
  8618. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8619. loadDynamicRouting();
  8620. }
  8621. async function removeSelectedOspfAreaRange() {
  8622. const id = state.selectedOspfRow?.['area-ranges'];
  8623. if (!id) return;
  8624. if (!confirm('Delete selected area range?')) return;
  8625. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8626. loadDynamicRouting();
  8627. }
  8628. async function promptCommentOspfAreaRange() {
  8629. const id = state.selectedOspfRow?.['area-ranges'];
  8630. if (!id) return;
  8631. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8632. if (!r) return;
  8633. const comment = prompt('Enter comment for area range:', r.comment || '');
  8634. if (comment === null) return;
  8635. r.comment = comment;
  8636. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8637. loadDynamicRouting();
  8638. }
  8639. // --- 4. OSPF INTERFACE TEMPLATE ---
  8640. function switchOspfTemplateTab(tab) {
  8641. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8642. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8643. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8644. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8645. if (tab === 'general') {
  8646. if (tabGen) tabGen.classList.remove('hidden');
  8647. if (tabAuth) tabAuth.classList.add('hidden');
  8648. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8649. 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';
  8650. } else {
  8651. if (tabGen) tabGen.classList.add('hidden');
  8652. if (tabAuth) tabAuth.classList.remove('hidden');
  8653. 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';
  8654. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8655. }
  8656. }
  8657. function populateTemplateAreaDropdowns() {
  8658. const select = document.getElementById('modal-ospf-tmpl-area');
  8659. if (select) {
  8660. const cur = select.value;
  8661. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8662. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8663. if (cur) select.value = cur;
  8664. }
  8665. }
  8666. function openOspfTemplateModal(id = null) {
  8667. const isEdit = !!id;
  8668. populateTemplateAreaDropdowns();
  8669. switchOspfTemplateTab('general');
  8670. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8671. id: '',
  8672. interfaces: '',
  8673. area: 'Default',
  8674. networks: '',
  8675. network_type: 'broadcast',
  8676. cost: 1,
  8677. priority: 128,
  8678. passive: false,
  8679. hello_interval: 10,
  8680. dead_interval: 40,
  8681. auth: 'none',
  8682. auth_key: '',
  8683. disabled: false,
  8684. comment: ''
  8685. };
  8686. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8687. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8688. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8689. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8690. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8691. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8692. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8693. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8694. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8695. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8696. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8697. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8698. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8699. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8700. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8701. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8702. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8703. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8704. }
  8705. function openEditOspfTemplateModal(id) {
  8706. openOspfTemplateModal(id);
  8707. }
  8708. function closeOspfTemplateModal() {
  8709. document.getElementById('ospf-template-modal').classList.add('hidden');
  8710. }
  8711. async function submitOspfTemplate(e) {
  8712. if (e) e.preventDefault();
  8713. const payload = {
  8714. id: document.getElementById('modal-ospf-tmpl-id').value,
  8715. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8716. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8717. area: document.getElementById('modal-ospf-tmpl-area').value,
  8718. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8719. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8720. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8721. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8722. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8723. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8724. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8725. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8726. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8727. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8728. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8729. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8730. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8731. };
  8732. try {
  8733. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8734. method: 'POST',
  8735. headers: { 'Content-Type': 'application/json' },
  8736. body: JSON.stringify(payload)
  8737. });
  8738. if (res.ok) {
  8739. closeOspfTemplateModal();
  8740. showToast('Saved', 'Interface template saved', 'success');
  8741. loadDynamicRouting();
  8742. } else {
  8743. const err = await res.json();
  8744. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8745. }
  8746. } catch (err) {
  8747. showToast('Error', err.message, 'error');
  8748. }
  8749. }
  8750. function applyOspfTemplateForm() {
  8751. submitOspfTemplate(null);
  8752. }
  8753. function copyOspfTemplate() {
  8754. document.getElementById('modal-ospf-tmpl-id').value = '';
  8755. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8756. showToast('Copied', 'Duplicated as new template', 'info');
  8757. }
  8758. async function deleteCurrentOspfTemplate() {
  8759. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8760. if (!id) return;
  8761. if (!confirm('Delete this interface template?')) return;
  8762. try {
  8763. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8764. closeOspfTemplateModal();
  8765. showToast('Removed', 'Interface template deleted', 'success');
  8766. loadDynamicRouting();
  8767. } catch (err) {
  8768. showToast('Error', err.message, 'error');
  8769. }
  8770. }
  8771. async function enableSelectedOspfTemplate() {
  8772. const id = state.selectedOspfRow?.templates;
  8773. if (!id) return;
  8774. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8775. method: 'POST',
  8776. headers: { 'Content-Type': 'application/json' },
  8777. body: JSON.stringify({ disabled: false })
  8778. });
  8779. loadDynamicRouting();
  8780. }
  8781. async function disableSelectedOspfTemplate() {
  8782. const id = state.selectedOspfRow?.templates;
  8783. if (!id) return;
  8784. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8785. method: 'POST',
  8786. headers: { 'Content-Type': 'application/json' },
  8787. body: JSON.stringify({ disabled: true })
  8788. });
  8789. loadDynamicRouting();
  8790. }
  8791. async function removeSelectedOspfTemplate() {
  8792. const id = state.selectedOspfRow?.templates;
  8793. if (!id) return;
  8794. if (!confirm('Delete selected interface template?')) return;
  8795. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8796. loadDynamicRouting();
  8797. }
  8798. async function promptCommentOspfTemplate() {
  8799. const id = state.selectedOspfRow?.templates;
  8800. if (!id) return;
  8801. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8802. if (!tmpl) return;
  8803. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8804. if (comment === null) return;
  8805. tmpl.comment = comment;
  8806. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8807. method: 'POST',
  8808. headers: { 'Content-Type': 'application/json' },
  8809. body: JSON.stringify(tmpl)
  8810. });
  8811. loadDynamicRouting();
  8812. }
  8813. // --- 5. OSPF STATIC NEIGHBOR ---
  8814. function populateStaticNbrAreaDropdowns() {
  8815. const select = document.getElementById('modal-ospf-snbr-area');
  8816. if (select) {
  8817. const cur = select.value;
  8818. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8819. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8820. if (cur) select.value = cur;
  8821. }
  8822. }
  8823. function openOspfStaticNbrModal(id = null) {
  8824. const isEdit = !!id;
  8825. populateStaticNbrAreaDropdowns();
  8826. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8827. id: '',
  8828. address: '',
  8829. area: 'Default',
  8830. poll_interval: 120,
  8831. cost: 1,
  8832. disabled: false,
  8833. comment: ''
  8834. };
  8835. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8836. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8837. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8838. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8839. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8840. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8841. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8842. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8843. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8844. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8845. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8846. }
  8847. function openEditOspfStaticNbrModal(id) {
  8848. openOspfStaticNbrModal(id);
  8849. }
  8850. function closeOspfStaticNbrModal() {
  8851. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8852. }
  8853. async function submitOspfStaticNbr(e) {
  8854. if (e) e.preventDefault();
  8855. const payload = {
  8856. id: document.getElementById('modal-ospf-snbr-id').value,
  8857. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8858. area: document.getElementById('modal-ospf-snbr-area').value,
  8859. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8860. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8861. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8862. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8863. };
  8864. try {
  8865. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8866. method: 'POST',
  8867. headers: { 'Content-Type': 'application/json' },
  8868. body: JSON.stringify(payload)
  8869. });
  8870. if (res.ok) {
  8871. closeOspfStaticNbrModal();
  8872. showToast('Saved', 'Static neighbor saved', 'success');
  8873. loadDynamicRouting();
  8874. } else {
  8875. const err = await res.json();
  8876. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8877. }
  8878. } catch (err) {
  8879. showToast('Error', err.message, 'error');
  8880. }
  8881. }
  8882. function applyOspfStaticNbrForm() {
  8883. submitOspfStaticNbr(null);
  8884. }
  8885. async function deleteCurrentOspfStaticNbr() {
  8886. const id = document.getElementById('modal-ospf-snbr-id').value;
  8887. if (!id) return;
  8888. if (!confirm('Delete this static neighbor?')) return;
  8889. try {
  8890. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8891. closeOspfStaticNbrModal();
  8892. showToast('Removed', 'Static neighbor removed', 'success');
  8893. loadDynamicRouting();
  8894. } catch (err) {
  8895. showToast('Error', err.message, 'error');
  8896. }
  8897. }
  8898. async function enableSelectedOspfStaticNbr() {
  8899. const id = state.selectedOspfRow?.['static-nbrs'];
  8900. if (!id) return;
  8901. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8902. if (!n) return;
  8903. n.disabled = false;
  8904. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8905. loadDynamicRouting();
  8906. }
  8907. async function disableSelectedOspfStaticNbr() {
  8908. const id = state.selectedOspfRow?.['static-nbrs'];
  8909. if (!id) return;
  8910. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8911. if (!n) return;
  8912. n.disabled = true;
  8913. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8914. loadDynamicRouting();
  8915. }
  8916. async function removeSelectedOspfStaticNbr() {
  8917. const id = state.selectedOspfRow?.['static-nbrs'];
  8918. if (!id) return;
  8919. if (!confirm('Delete selected static neighbor?')) return;
  8920. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8921. loadDynamicRouting();
  8922. }
  8923. async function promptCommentOspfStaticNbr() {
  8924. const id = state.selectedOspfRow?.['static-nbrs'];
  8925. if (!id) return;
  8926. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8927. if (!n) return;
  8928. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8929. if (comment === null) return;
  8930. n.comment = comment;
  8931. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8932. loadDynamicRouting();
  8933. }
  8934. // Backward-compat aliases
  8935. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8936. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8937. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8938. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8939. function deleteOspfInterface(id) {
  8940. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8941. }
  8942. function toggleOspfInterfaceState(id, disabled) {
  8943. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8944. method: 'POST',
  8945. headers: { 'Content-Type': 'application/json' },
  8946. body: JSON.stringify({ disabled })
  8947. }).then(() => loadDynamicRouting());
  8948. }
  8949. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8950. function deleteOspfArea(id) {
  8951. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8952. }
  8953. // ============================================================================
  8954. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8955. // ============================================================================
  8956. function switchBridgeSubTab(tab) {
  8957. state.bridgeSubTab = tab;
  8958. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8959. tabs.forEach(t => {
  8960. const panel = document.getElementById(`bridge-subtab-${t}`);
  8961. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8962. if (panel) {
  8963. if (t === tab) panel.classList.remove('hidden');
  8964. else panel.classList.add('hidden');
  8965. }
  8966. if (btn) {
  8967. if (t === tab) {
  8968. 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';
  8969. } else {
  8970. 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';
  8971. }
  8972. }
  8973. });
  8974. const addBtn = document.getElementById('bridge-top-action-btn');
  8975. if (addBtn) {
  8976. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8977. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8978. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8979. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8980. }
  8981. if (tab === 'hosts') loadBridgeHosts();
  8982. setTimeout(initTableSorting, 50);
  8983. }
  8984. function openCurrentBridgeModal() {
  8985. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8986. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8987. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8988. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8989. }
  8990. async function loadBridge() {
  8991. try {
  8992. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8993. fetch(`${API_BASE}/bridge/bridges`),
  8994. fetch(`${API_BASE}/bridge/ports`),
  8995. fetch(`${API_BASE}/bridge/vlans`),
  8996. fetch(`${API_BASE}/bridge/summary`),
  8997. fetch(`${API_BASE}/vpn/eoip`),
  8998. fetch(`${API_BASE}/vlans`)
  8999. ]);
  9000. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9001. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9002. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9003. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9004. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9005. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9006. // Badges & Stats
  9007. const bBridges = document.getElementById('bridge-badge-bridges');
  9008. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9009. const bPorts = document.getElementById('bridge-badge-ports');
  9010. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9011. const bVlans = document.getElementById('bridge-badge-vlans');
  9012. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9013. const bHosts = document.getElementById('bridge-badge-hosts');
  9014. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9015. const sBr = document.getElementById('bridge-stat-bridges');
  9016. if (sBr) sBr.innerText = (state.bridges || []).length;
  9017. const sPorts = document.getElementById('bridge-stat-ports');
  9018. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9019. const sHosts = document.getElementById('bridge-stat-hosts');
  9020. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9021. renderBridges();
  9022. renderBridgePorts();
  9023. renderBridgeVLANs();
  9024. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9025. } catch (err) {
  9026. console.error('Failed to load bridge subsystem:', err);
  9027. }
  9028. }
  9029. // ----------------- Bridges -----------------
  9030. function renderBridges() {
  9031. const tbody = document.getElementById('bridge-table-body');
  9032. const empty = document.getElementById('bridge-empty-bridges');
  9033. const countBadge = document.getElementById('bridge-count-badge');
  9034. if (!tbody) return;
  9035. tbody.innerHTML = '';
  9036. const bridges = state.bridges || [];
  9037. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9038. if (bridges.length === 0) {
  9039. empty?.classList.remove('hidden');
  9040. return;
  9041. }
  9042. empty?.classList.add('hidden');
  9043. bridges.forEach((b, idx) => {
  9044. const tr = document.createElement('tr');
  9045. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9046. // Format IP addresses pill list
  9047. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9048. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9049. ipsHtml = b.ip_addresses.map(ip => `
  9050. <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">
  9051. <span>${ip}</span>
  9052. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9053. </span>
  9054. `).join(' ');
  9055. }
  9056. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9057. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9058. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9059. tr.innerHTML = `
  9060. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9061. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9062. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9063. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9064. </td>
  9065. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9066. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9067. <td class="py-2.5 px-3">
  9068. <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>
  9069. </td>
  9070. <td class="py-2.5 px-3 text-center">
  9071. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9072. </td>
  9073. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9074. <td class="py-2.5 px-3">
  9075. <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>
  9076. </td>
  9077. <td class="py-2.5 px-3">
  9078. <div class="flex items-center gap-1.5 flex-wrap">
  9079. ${ipsHtml}
  9080. <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>
  9081. </div>
  9082. </td>
  9083. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9084. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9085. </td>
  9086. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9087. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9088. <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>
  9089. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9090. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9091. </td>
  9092. `;
  9093. tbody.appendChild(tr);
  9094. });
  9095. }
  9096. function openAddBridgeModal() {
  9097. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9098. document.getElementById('bridge-modal-id').value = '';
  9099. document.getElementById('bridge-modal-name').value = 'bridge1';
  9100. document.getElementById('bridge-modal-name').disabled = false;
  9101. document.getElementById('bridge-modal-mtu').value = '1500';
  9102. document.getElementById('bridge-modal-mac').value = '';
  9103. document.getElementById('bridge-modal-stp').value = 'rstp';
  9104. document.getElementById('bridge-modal-priority').value = '32768';
  9105. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9106. document.getElementById('bridge-modal-pvid').value = '1';
  9107. document.getElementById('bridge-modal-fastforward').checked = true;
  9108. document.getElementById('bridge-modal-comment').value = '';
  9109. document.getElementById('bridge-modal-disabled').checked = false;
  9110. toggleBridgeModalVlanFiltering();
  9111. document.getElementById('bridge-modal').classList.remove('hidden');
  9112. }
  9113. function openEditBridgeModal(id) {
  9114. const b = (state.bridges || []).find(x => x.id === id);
  9115. if (!b) return;
  9116. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9117. document.getElementById('bridge-modal-id').value = b.id;
  9118. document.getElementById('bridge-modal-name').value = b.name;
  9119. document.getElementById('bridge-modal-name').disabled = true;
  9120. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9121. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9122. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9123. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9124. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9125. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9126. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9127. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9128. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9129. toggleBridgeModalVlanFiltering();
  9130. document.getElementById('bridge-modal').classList.remove('hidden');
  9131. }
  9132. function closeBridgeModal() {
  9133. document.getElementById('bridge-modal').classList.add('hidden');
  9134. }
  9135. function toggleBridgeModalVlanFiltering() {
  9136. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9137. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9138. if (pvidBox) {
  9139. if (chk) pvidBox.classList.remove('opacity-40');
  9140. else pvidBox.classList.add('opacity-40');
  9141. }
  9142. }
  9143. async function submitSaveBridge(e) {
  9144. e.preventDefault();
  9145. const id = document.getElementById('bridge-modal-id').value;
  9146. const name = document.getElementById('bridge-modal-name').value.trim();
  9147. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9148. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9149. const stp = document.getElementById('bridge-modal-stp').value;
  9150. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9151. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9152. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9153. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9154. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9155. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9156. try {
  9157. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9158. method: 'POST',
  9159. headers: { 'Content-Type': 'application/json' },
  9160. body: JSON.stringify({
  9161. id,
  9162. name,
  9163. mtu,
  9164. mac_address: mac,
  9165. stp,
  9166. priority,
  9167. vlan_filtering: vlanFiltering,
  9168. pvid,
  9169. fast_forward: fastForward,
  9170. comment,
  9171. disabled
  9172. })
  9173. });
  9174. if (res.ok) {
  9175. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9176. closeBridgeModal();
  9177. loadBridge();
  9178. fetchData(false);
  9179. } else {
  9180. const err = await res.json();
  9181. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9182. }
  9183. } catch (err) {
  9184. showToast('Error', err.message, 'error');
  9185. }
  9186. }
  9187. async function toggleBridgeState(id, disabled) {
  9188. try {
  9189. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9190. method: 'POST',
  9191. headers: { 'Content-Type': 'application/json' },
  9192. body: JSON.stringify({ disabled })
  9193. });
  9194. if (res.ok) {
  9195. loadBridge();
  9196. fetchData(false);
  9197. }
  9198. } catch (err) {
  9199. showToast('Error', err.message, 'error');
  9200. }
  9201. }
  9202. async function deleteBridge(id) {
  9203. const b = (state.bridges || []).find(x => x.id === id);
  9204. const name = b ? b.name : id;
  9205. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9206. try {
  9207. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9208. if (res.ok) {
  9209. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9210. loadBridge();
  9211. fetchData(false);
  9212. } else {
  9213. const err = await res.json();
  9214. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9215. }
  9216. } catch (err) {
  9217. showToast('Error', err.message, 'error');
  9218. }
  9219. }
  9220. // ----------------- Bridge IP Assignments -----------------
  9221. function openAddBridgeIPModal(id, name) {
  9222. document.getElementById('bridge-ip-modal-id').value = id;
  9223. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9224. document.getElementById('bridge-ip-modal-cidr').value = '';
  9225. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9226. }
  9227. function closeBridgeIPModal() {
  9228. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9229. }
  9230. async function submitAddBridgeIP(e) {
  9231. e.preventDefault();
  9232. const id = document.getElementById('bridge-ip-modal-id').value;
  9233. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9234. try {
  9235. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9236. method: 'POST',
  9237. headers: { 'Content-Type': 'application/json' },
  9238. body: JSON.stringify({ ip })
  9239. });
  9240. if (res.ok) {
  9241. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9242. closeBridgeIPModal();
  9243. loadBridge();
  9244. fetchData(false);
  9245. } else {
  9246. const err = await res.json();
  9247. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9248. }
  9249. } catch (err) {
  9250. showToast('Error', err.message, 'error');
  9251. }
  9252. }
  9253. async function deleteBridgeIP(id, ip) {
  9254. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9255. try {
  9256. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9257. method: 'DELETE',
  9258. headers: { 'Content-Type': 'application/json' },
  9259. body: JSON.stringify({ ip })
  9260. });
  9261. if (res.ok) {
  9262. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9263. loadBridge();
  9264. fetchData(false);
  9265. }
  9266. } catch (err) {
  9267. showToast('Error', err.message, 'error');
  9268. }
  9269. }
  9270. // ----------------- Bridge Ports -----------------
  9271. function renderBridgePorts() {
  9272. const tbody = document.getElementById('bridge-ports-table-body');
  9273. const empty = document.getElementById('bridge-empty-ports');
  9274. const countBadge = document.getElementById('bridge-ports-count-badge');
  9275. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9276. if (!tbody) return;
  9277. tbody.innerHTML = '';
  9278. // Update filter select
  9279. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9280. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9281. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9282. if (ports.length === 0) {
  9283. empty?.classList.remove('hidden');
  9284. return;
  9285. }
  9286. empty?.classList.add('hidden');
  9287. ports.forEach((p, idx) => {
  9288. const tr = document.createElement('tr');
  9289. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9290. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9291. tr.innerHTML = `
  9292. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9293. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9294. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9295. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9296. </td>
  9297. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9298. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9299. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9300. <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>
  9301. <td class="py-2.5 px-3">
  9302. ${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>'}
  9303. </td>
  9304. <td class="py-2.5 px-3">
  9305. <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>
  9306. </td>
  9307. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9308. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9309. <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>
  9310. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9311. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9312. </td>
  9313. `;
  9314. tbody.appendChild(tr);
  9315. });
  9316. }
  9317. function openAddBridgePortModal() {
  9318. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9319. document.getElementById('bridge-port-modal-id').value = '';
  9320. populateBridgeSelect('bridge-port-modal-bridge');
  9321. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9322. document.getElementById('bridge-port-modal-pvid').value = '1';
  9323. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9324. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9325. document.getElementById('bridge-port-modal-horizon').value = '0';
  9326. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9327. document.getElementById('bridge-port-modal-priority').value = '128';
  9328. document.getElementById('bridge-port-modal-learn').checked = true;
  9329. document.getElementById('bridge-port-modal-comment').value = '';
  9330. document.getElementById('bridge-port-modal-disabled').checked = false;
  9331. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9332. }
  9333. function openEditBridgePortModal(id) {
  9334. const p = (state.bridgePorts || []).find(x => x.id === id);
  9335. if (!p) return;
  9336. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9337. document.getElementById('bridge-port-modal-id').value = p.id;
  9338. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9339. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9340. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9341. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9342. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9343. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9344. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9345. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9346. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9347. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9348. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9349. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9350. }
  9351. function closeBridgePortModal() {
  9352. document.getElementById('bridge-port-modal').classList.add('hidden');
  9353. }
  9354. async function submitSaveBridgePort(e) {
  9355. e.preventDefault();
  9356. const id = document.getElementById('bridge-port-modal-id').value;
  9357. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9358. const iface = document.getElementById('bridge-port-modal-interface').value;
  9359. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9360. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9361. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9362. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9363. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9364. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9365. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9366. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9367. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9368. try {
  9369. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9370. method: 'POST',
  9371. headers: { 'Content-Type': 'application/json' },
  9372. body: JSON.stringify({
  9373. id,
  9374. bridge,
  9375. interface: iface,
  9376. pvid,
  9377. frame_types: frameTypes,
  9378. ingress_filtering: ingressFiltering,
  9379. horizon,
  9380. path_cost: pathCost,
  9381. priority,
  9382. learn,
  9383. comment,
  9384. disabled
  9385. })
  9386. });
  9387. if (res.ok) {
  9388. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9389. closeBridgePortModal();
  9390. loadBridge();
  9391. fetchData(false);
  9392. } else {
  9393. const err = await res.json();
  9394. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9395. }
  9396. } catch (err) {
  9397. showToast('Error', err.message, 'error');
  9398. }
  9399. }
  9400. async function toggleBridgePortState(id, disabled) {
  9401. try {
  9402. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9403. method: 'POST',
  9404. headers: { 'Content-Type': 'application/json' },
  9405. body: JSON.stringify({ disabled })
  9406. });
  9407. if (res.ok) {
  9408. loadBridge();
  9409. fetchData(false);
  9410. }
  9411. } catch (err) {
  9412. showToast('Error', err.message, 'error');
  9413. }
  9414. }
  9415. async function deleteBridgePort(id) {
  9416. const p = (state.bridgePorts || []).find(x => x.id === id);
  9417. const iface = p ? p.interface : id;
  9418. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9419. try {
  9420. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9421. if (res.ok) {
  9422. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9423. loadBridge();
  9424. fetchData(false);
  9425. }
  9426. } catch (err) {
  9427. showToast('Error', err.message, 'error');
  9428. }
  9429. }
  9430. // ----------------- Bridge VLANs -----------------
  9431. function renderBridgeVLANs() {
  9432. const tbody = document.getElementById('bridge-vlans-table-body');
  9433. const empty = document.getElementById('bridge-empty-vlans');
  9434. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9435. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9436. if (!tbody) return;
  9437. tbody.innerHTML = '';
  9438. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9439. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9440. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9441. if (vlans.length === 0) {
  9442. empty?.classList.remove('hidden');
  9443. return;
  9444. }
  9445. empty?.classList.add('hidden');
  9446. vlans.forEach((v, idx) => {
  9447. const tr = document.createElement('tr');
  9448. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9449. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9450. ? 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(' ')
  9451. : '<span class="text-slate-600">none</span>';
  9452. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9453. ? 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(' ')
  9454. : '<span class="text-slate-600">none</span>';
  9455. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9456. tr.innerHTML = `
  9457. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9458. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9459. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9460. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9461. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9462. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9463. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9464. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9465. <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>
  9466. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9467. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9468. </td>
  9469. `;
  9470. tbody.appendChild(tr);
  9471. });
  9472. }
  9473. function openAddBridgeVLANModal() {
  9474. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9475. document.getElementById('bridge-vlan-modal-id').value = '';
  9476. populateBridgeSelect('bridge-vlan-modal-bridge');
  9477. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9478. document.getElementById('bridge-vlan-modal-comment').value = '';
  9479. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9480. updateBridgeVlanPortCheckboxes();
  9481. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9482. }
  9483. function openEditBridgeVLANModal(id) {
  9484. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9485. if (!v) return;
  9486. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9487. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9488. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9489. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9490. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9491. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9492. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9493. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9494. }
  9495. function closeBridgeVlanModal() {
  9496. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9497. }
  9498. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9499. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9500. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9501. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9502. if (!taggedBox || !untaggedBox) return;
  9503. // Ports belonging to the selected bridge
  9504. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9505. if (memberPorts.length === 0) {
  9506. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9507. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9508. return;
  9509. }
  9510. taggedBox.innerHTML = memberPorts.map(p => `
  9511. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9512. <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">
  9513. <span>${p.interface}</span>
  9514. </label>
  9515. `).join('');
  9516. untaggedBox.innerHTML = memberPorts.map(p => `
  9517. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9518. <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">
  9519. <span>${p.interface}</span>
  9520. </label>
  9521. `).join('');
  9522. }
  9523. async function submitSaveBridgeVLAN(e) {
  9524. e.preventDefault();
  9525. const id = document.getElementById('bridge-vlan-modal-id').value;
  9526. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9527. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9528. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9529. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9530. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9531. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9532. try {
  9533. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9534. method: 'POST',
  9535. headers: { 'Content-Type': 'application/json' },
  9536. body: JSON.stringify({
  9537. id,
  9538. bridge,
  9539. vlan_ids: vlanIDs,
  9540. tagged,
  9541. untagged,
  9542. comment,
  9543. disabled
  9544. })
  9545. });
  9546. if (res.ok) {
  9547. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9548. closeBridgeVlanModal();
  9549. loadBridge();
  9550. } else {
  9551. const err = await res.json();
  9552. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9553. }
  9554. } catch (err) {
  9555. showToast('Error', err.message, 'error');
  9556. }
  9557. }
  9558. async function toggleBridgeVLANState(id, disabled) {
  9559. try {
  9560. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9561. method: 'POST',
  9562. headers: { 'Content-Type': 'application/json' },
  9563. body: JSON.stringify({ disabled })
  9564. });
  9565. if (res.ok) loadBridge();
  9566. } catch (err) {
  9567. showToast('Error', err.message, 'error');
  9568. }
  9569. }
  9570. async function deleteBridgeVLAN(id) {
  9571. if (!confirm('Delete this bridge VLAN entry?')) return;
  9572. try {
  9573. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9574. if (res.ok) {
  9575. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9576. loadBridge();
  9577. }
  9578. } catch (err) {
  9579. showToast('Error', err.message, 'error');
  9580. }
  9581. }
  9582. // ----------------- Hosts / MAC Table -----------------
  9583. async function loadBridgeHosts() {
  9584. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9585. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9586. try {
  9587. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9588. const res = await fetch(url);
  9589. if (res.ok) {
  9590. state.bridgeHosts = await res.json();
  9591. renderBridgeHosts();
  9592. }
  9593. } catch (err) {
  9594. console.error('Failed to load bridge hosts:', err);
  9595. }
  9596. }
  9597. function renderBridgeHosts() {
  9598. const tbody = document.getElementById('bridge-hosts-table-body');
  9599. const empty = document.getElementById('bridge-empty-hosts');
  9600. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9601. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9602. if (!tbody) return;
  9603. tbody.innerHTML = '';
  9604. const hosts = (state.bridgeHosts || []).filter(h => {
  9605. if (!search) return true;
  9606. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9607. });
  9608. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9609. if (hosts.length === 0) {
  9610. empty?.classList.remove('hidden');
  9611. return;
  9612. }
  9613. empty?.classList.add('hidden');
  9614. hosts.forEach(h => {
  9615. const tr = document.createElement('tr');
  9616. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9617. let flagBadges = '';
  9618. 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>';
  9619. 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>';
  9620. 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>';
  9621. tr.innerHTML = `
  9622. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9623. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9624. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9625. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9626. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9627. <td class="py-2.5 px-3">${flagBadges}</td>
  9628. `;
  9629. tbody.appendChild(tr);
  9630. });
  9631. }
  9632. async function flushBridgeHosts() {
  9633. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9634. if (!selBridge) {
  9635. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9636. return;
  9637. }
  9638. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9639. try {
  9640. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9641. method: 'POST',
  9642. headers: { 'Content-Type': 'application/json' },
  9643. body: JSON.stringify({ bridge: selBridge })
  9644. });
  9645. if (res.ok) {
  9646. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9647. loadBridgeHosts();
  9648. }
  9649. } catch (err) {
  9650. showToast('Error', err.message, 'error');
  9651. }
  9652. }
  9653. // ----------------- Helpers -----------------
  9654. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9655. const sel = document.getElementById(selectId);
  9656. if (!sel) return;
  9657. const prevVal = currentVal || sel.value;
  9658. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9659. (state.bridges || []).forEach(b => {
  9660. const opt = document.createElement('option');
  9661. opt.value = b.name;
  9662. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9663. if (b.name === prevVal) opt.selected = true;
  9664. sel.appendChild(opt);
  9665. });
  9666. }
  9667. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9668. const sel = document.getElementById(selectId);
  9669. if (!sel) return;
  9670. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9671. // 1. Physical Interfaces
  9672. const grpPhys = document.createElement('optgroup');
  9673. grpPhys.label = 'Physical Interfaces';
  9674. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9675. const opt = document.createElement('option');
  9676. opt.value = i.name;
  9677. opt.innerText = `${i.name} (${i.role || i.type})`;
  9678. if (i.name === currentVal) opt.selected = true;
  9679. grpPhys.appendChild(opt);
  9680. });
  9681. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9682. // 2. VLAN Sub-interfaces
  9683. const grpVlans = document.createElement('optgroup');
  9684. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9685. (state.vlans || []).forEach(v => {
  9686. const opt = document.createElement('option');
  9687. opt.value = v.name;
  9688. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9689. if (v.name === currentVal) opt.selected = true;
  9690. grpVlans.appendChild(opt);
  9691. });
  9692. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9693. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9694. const grpEoip = document.createElement('optgroup');
  9695. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9696. (state.eoipTunnels || []).forEach(t => {
  9697. const opt = document.createElement('option');
  9698. opt.value = t.name;
  9699. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9700. if (t.name === currentVal) opt.selected = true;
  9701. grpEoip.appendChild(opt);
  9702. });
  9703. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9704. }
  9705. // -------------------------------------------------------------
  9706. // RouterOS v7 Routing Filters Management (/routing filter)
  9707. // -------------------------------------------------------------
  9708. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9709. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9710. if (!state.rfSort) state.rfSort = {};
  9711. function switchRoutingFilterTab(tab) {
  9712. state.activeRoutingFilterTab = tab;
  9713. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9714. tabs.forEach(t => {
  9715. const btn = document.getElementById(`tab-rf-${t}`);
  9716. const content = document.getElementById(`tab-content-rf-${t}`);
  9717. if (btn) {
  9718. if (t === tab) {
  9719. 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';
  9720. } else {
  9721. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9722. }
  9723. }
  9724. if (content) {
  9725. if (t === tab) content.classList.remove('hidden');
  9726. else content.classList.add('hidden');
  9727. }
  9728. });
  9729. const chainContainer = document.getElementById('rf-chain-filter-container');
  9730. if (chainContainer) {
  9731. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9732. else chainContainer.classList.add('hidden');
  9733. }
  9734. renderRoutingFilters();
  9735. }
  9736. function selectFilterRow(tab, id) {
  9737. if (state.selectedFilterRow[tab] === id) {
  9738. delete state.selectedFilterRow[tab];
  9739. } else {
  9740. state.selectedFilterRow[tab] = id;
  9741. }
  9742. if (tab === 'rules') renderRoutingFilterRules();
  9743. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9744. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9745. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9746. }
  9747. function openRoutingFilterNewModal() {
  9748. const tab = state.activeRoutingFilterTab || 'rules';
  9749. if (tab === 'rules') openAddRoutingFilterModal();
  9750. else if (tab === 'select-rules') openAddSelectRuleModal();
  9751. else if (tab === 'community-lists') openAddCommunityListModal();
  9752. else if (tab === 'as-lists') openAddASListModal();
  9753. }
  9754. function toggleSelectedRoutingFilter(disabled) {
  9755. const tab = state.activeRoutingFilterTab || 'rules';
  9756. const id = state.selectedFilterRow[tab];
  9757. if (!id) {
  9758. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9759. return;
  9760. }
  9761. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9762. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9763. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9764. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9765. }
  9766. function removeSelectedRoutingFilter() {
  9767. const tab = state.activeRoutingFilterTab || 'rules';
  9768. const id = state.selectedFilterRow[tab];
  9769. if (!id) {
  9770. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9771. return;
  9772. }
  9773. if (tab === 'rules') deleteRoutingFilter(id);
  9774. else if (tab === 'select-rules') deleteSelectRule(id);
  9775. else if (tab === 'community-lists') deleteCommunityList(id);
  9776. else if (tab === 'as-lists') deleteASList(id);
  9777. }
  9778. function searchRoutingFilters(q) {
  9779. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9780. renderRoutingFilters();
  9781. }
  9782. function sortFilterTable(tab, col) {
  9783. if (!state.rfSort) state.rfSort = {};
  9784. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9785. if (state.rfSort[tab].col === col) {
  9786. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9787. } else {
  9788. state.rfSort[tab].col = col;
  9789. state.rfSort[tab].asc = true;
  9790. }
  9791. const asc = state.rfSort[tab].asc;
  9792. let list = [];
  9793. if (tab === 'rules') list = state.routingFilters || [];
  9794. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9795. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9796. else if (tab === 'as-lists') list = state.routingASLists || [];
  9797. list.sort((a, b) => {
  9798. let valA = a[col] ?? '';
  9799. let valB = b[col] ?? '';
  9800. if (col === 'flags') {
  9801. valA = a.disabled ? 'X' : 'A';
  9802. valB = b.disabled ? 'X' : 'A';
  9803. }
  9804. if (typeof valA === 'number' && typeof valB === 'number') {
  9805. return asc ? valA - valB : valB - valA;
  9806. }
  9807. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9808. });
  9809. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9810. allCols.forEach(c => {
  9811. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9812. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9813. });
  9814. if (tab === 'rules') renderRoutingFilterRules();
  9815. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9816. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9817. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9818. }
  9819. function renderRoutingFilters() {
  9820. const navBadge = document.getElementById('badge-filters-count');
  9821. const allRules = state.routingFilters || [];
  9822. if (navBadge) navBadge.innerText = allRules.length;
  9823. // Populate chain filter select options and datalist
  9824. const chainSelect = document.getElementById('routing-filter-chain-select');
  9825. const chainDatalist = document.getElementById('dl-routing-chains');
  9826. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9827. if (chainSelect) {
  9828. const currentVal = state.filterChainSelected || 'all';
  9829. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9830. uniqueChains.map(ch => {
  9831. const count = allRules.filter(r => r.chain === ch).length;
  9832. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9833. }).join('');
  9834. chainSelect.value = currentVal;
  9835. }
  9836. if (chainDatalist) {
  9837. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9838. }
  9839. renderRoutingFilterRules();
  9840. renderRoutingFilterSelectRules();
  9841. renderRoutingFilterCommunityLists();
  9842. renderRoutingFilterASLists();
  9843. }
  9844. function filterRoutingFiltersByChain(chain) {
  9845. state.filterChainSelected = chain;
  9846. renderRoutingFilters();
  9847. }
  9848. // -------------------------------------------------------------
  9849. // TAB 1: RULES (/routing filter rule)
  9850. // -------------------------------------------------------------
  9851. function renderRoutingFilterRules() {
  9852. const tbody = document.getElementById('routing-filter-rules-tbody');
  9853. if (!tbody) return;
  9854. const empty = document.getElementById('rf-rules-empty');
  9855. const statusCount = document.getElementById('rf-status-count');
  9856. let list = (state.routingFilters || []).slice();
  9857. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9858. list = list.filter(r => r.chain === state.filterChainSelected);
  9859. }
  9860. const q = state.rfSearchQuery;
  9861. if (q) {
  9862. list = list.filter(r =>
  9863. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9864. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9865. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9866. (r.comment && r.comment.toLowerCase().includes(q))
  9867. );
  9868. }
  9869. if (!state.rfSort?.['rules']) {
  9870. list.sort((a, b) => {
  9871. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9872. return (a.rule_order || 0) - (b.rule_order || 0);
  9873. });
  9874. }
  9875. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9876. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9877. }
  9878. if (list.length === 0) {
  9879. tbody.innerHTML = '';
  9880. if (empty) empty.classList.remove('hidden');
  9881. return;
  9882. }
  9883. if (empty) empty.classList.add('hidden');
  9884. tbody.innerHTML = list.map(r => {
  9885. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9886. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9887. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9888. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9889. let ruleDisplay = '';
  9890. if (r.rule && r.rule.trim() !== '') {
  9891. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9892. } else {
  9893. let conds = [];
  9894. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9895. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9896. let act = r.action || 'accept';
  9897. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9898. }
  9899. return `
  9900. <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'}">
  9901. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9902. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9903. <td class="py-2 px-3">
  9904. <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>
  9905. </td>
  9906. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9907. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9908. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9909. <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>
  9910. <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>
  9911. <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'}">
  9912. ${r.disabled ? 'Enable' : 'Disable'}
  9913. </button>
  9914. <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">
  9915. Edit
  9916. </button>
  9917. <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">
  9918. ✕
  9919. </button>
  9920. </td>
  9921. </tr>
  9922. `;
  9923. }).join('');
  9924. }
  9925. // -------------------------------------------------------------
  9926. // TAB 2: SELECT RULES (/routing filter select-rule)
  9927. // -------------------------------------------------------------
  9928. function renderRoutingFilterSelectRules() {
  9929. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9930. if (!tbody) return;
  9931. const empty = document.getElementById('rf-select-rules-empty');
  9932. const statusCount = document.getElementById('rf-status-count');
  9933. let list = (state.routingSelectRules || []).slice();
  9934. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9935. list = list.filter(r => r.chain === state.filterChainSelected);
  9936. }
  9937. const q = state.rfSearchQuery;
  9938. if (q) {
  9939. list = list.filter(r =>
  9940. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9941. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9942. (r.comment && r.comment.toLowerCase().includes(q))
  9943. );
  9944. }
  9945. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9946. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9947. }
  9948. if (list.length === 0) {
  9949. tbody.innerHTML = '';
  9950. if (empty) empty.classList.remove('hidden');
  9951. return;
  9952. }
  9953. if (empty) empty.classList.add('hidden');
  9954. tbody.innerHTML = list.map(r => {
  9955. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9956. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9957. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9958. return `
  9959. <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'}">
  9960. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9961. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9962. <td class="py-2 px-3">
  9963. <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>
  9964. </td>
  9965. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9966. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9967. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9968. <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'}">
  9969. ${r.disabled ? 'Enable' : 'Disable'}
  9970. </button>
  9971. <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">
  9972. Edit
  9973. </button>
  9974. <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">
  9975. ✕
  9976. </button>
  9977. </td>
  9978. </tr>
  9979. `;
  9980. }).join('');
  9981. }
  9982. // -------------------------------------------------------------
  9983. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9984. // -------------------------------------------------------------
  9985. function renderRoutingFilterCommunityLists() {
  9986. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9987. if (!tbody) return;
  9988. const empty = document.getElementById('rf-comm-lists-empty');
  9989. const statusCount = document.getElementById('rf-status-count');
  9990. let list = (state.routingCommunityLists || []).slice();
  9991. const q = state.rfSearchQuery;
  9992. if (q) {
  9993. list = list.filter(cl =>
  9994. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9995. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9996. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9997. );
  9998. }
  9999. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10000. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10001. }
  10002. if (list.length === 0) {
  10003. tbody.innerHTML = '';
  10004. if (empty) empty.classList.remove('hidden');
  10005. return;
  10006. }
  10007. if (empty) empty.classList.add('hidden');
  10008. tbody.innerHTML = list.map(cl => {
  10009. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10010. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10011. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10012. const commBadges = (cl.communities || []).map(c =>
  10013. `<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>`
  10014. ).join(' ');
  10015. return `
  10016. <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'}">
  10017. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10018. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10019. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10020. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10021. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10022. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10023. <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'}">
  10024. ${cl.disabled ? 'Enable' : 'Disable'}
  10025. </button>
  10026. <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">
  10027. Edit
  10028. </button>
  10029. <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">
  10030. ✕
  10031. </button>
  10032. </td>
  10033. </tr>
  10034. `;
  10035. }).join('');
  10036. }
  10037. // -------------------------------------------------------------
  10038. // TAB 4: AS LISTS (/routing filter num-list)
  10039. // -------------------------------------------------------------
  10040. function renderRoutingFilterASLists() {
  10041. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10042. if (!tbody) return;
  10043. const empty = document.getElementById('rf-as-lists-empty');
  10044. const statusCount = document.getElementById('rf-status-count');
  10045. let list = (state.routingASLists || []).slice();
  10046. const q = state.rfSearchQuery;
  10047. if (q) {
  10048. list = list.filter(al =>
  10049. (al.name && al.name.toLowerCase().includes(q)) ||
  10050. (al.range && al.range.toLowerCase().includes(q)) ||
  10051. (al.comment && al.comment.toLowerCase().includes(q))
  10052. );
  10053. }
  10054. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10055. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10056. }
  10057. if (list.length === 0) {
  10058. tbody.innerHTML = '';
  10059. if (empty) empty.classList.remove('hidden');
  10060. return;
  10061. }
  10062. if (empty) empty.classList.add('hidden');
  10063. tbody.innerHTML = list.map(al => {
  10064. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10065. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10066. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10067. return `
  10068. <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'}">
  10069. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10070. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10071. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10072. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10073. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10074. <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'}">
  10075. ${al.disabled ? 'Enable' : 'Disable'}
  10076. </button>
  10077. <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">
  10078. Edit
  10079. </button>
  10080. <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">
  10081. ✕
  10082. </button>
  10083. </td>
  10084. </tr>
  10085. `;
  10086. }).join('');
  10087. }
  10088. // -------------------------------------------------------------
  10089. // SNIPPETS & WIZARD HELPERS
  10090. // -------------------------------------------------------------
  10091. function insertRuleSnippet(type) {
  10092. const textarea = document.getElementById('modal-rf-rule');
  10093. if (!textarea) return;
  10094. let snippet = '';
  10095. switch (type) {
  10096. case 'accept-default':
  10097. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10098. break;
  10099. case 'drop-rfc1918':
  10100. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10101. break;
  10102. case 'len-24':
  10103. snippet = 'if (dst-len > 24) { reject; }';
  10104. break;
  10105. case 'local-pref-150':
  10106. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10107. break;
  10108. case 'as-prepend-2':
  10109. snippet = 'set bgp-path-prepend 2; accept;';
  10110. break;
  10111. case 'set-comm':
  10112. snippet = 'set bgp-communities.add 65000:100; accept;';
  10113. break;
  10114. case 'match-comm':
  10115. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10116. break;
  10117. case 'reject-all':
  10118. snippet = 'reject;';
  10119. break;
  10120. }
  10121. if (!snippet) return;
  10122. if (!textarea.value.trim()) {
  10123. textarea.value = snippet;
  10124. } else {
  10125. textarea.value = textarea.value.trim() + '\n' + snippet;
  10126. }
  10127. }
  10128. function generateScriptFromWizard() {
  10129. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10130. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10131. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10132. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10133. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10134. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10135. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10136. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10137. const conds = [];
  10138. if (pfx) {
  10139. if (pfxLen) {
  10140. if (pfxLen.includes('-')) {
  10141. const parts = pfxLen.split('-');
  10142. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10143. } else {
  10144. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10145. }
  10146. } else {
  10147. conds.push(`dst in ${pfx}`);
  10148. }
  10149. }
  10150. if (proto && proto !== 'any') {
  10151. conds.push(`protocol ${proto}`);
  10152. }
  10153. if (asp) {
  10154. conds.push(`bgp-as-path "${asp}"`);
  10155. }
  10156. if (comm) {
  10157. conds.push(`bgp-communities includes ${comm}`);
  10158. }
  10159. const actions = [];
  10160. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10161. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10162. actions.push(`${act};`);
  10163. let code = '';
  10164. if (conds.length > 0) {
  10165. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10166. } else {
  10167. code = actions.join(' ');
  10168. }
  10169. const textarea = document.getElementById('modal-rf-rule');
  10170. if (textarea) textarea.value = code;
  10171. }
  10172. // -------------------------------------------------------------
  10173. // MODAL CRUD: RULES (/routing filter rule)
  10174. // -------------------------------------------------------------
  10175. function openAddRoutingFilterModal(defaultChain = '') {
  10176. const form = document.getElementById('routing-filter-form');
  10177. if (form) form.reset();
  10178. const idEl = document.getElementById('modal-rf-id');
  10179. if (idEl) idEl.value = '';
  10180. const titleEl = document.getElementById('modal-rf-title');
  10181. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10182. const chainEl = document.getElementById('modal-rf-chain');
  10183. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10184. const orderEl = document.getElementById('modal-rf-order');
  10185. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10186. const ruleEl = document.getElementById('modal-rf-rule');
  10187. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10188. const disEl = document.getElementById('modal-rf-disabled');
  10189. if (disEl) disEl.checked = false;
  10190. const modal = document.getElementById('modal-routing-filter');
  10191. if (modal) modal.classList.remove('hidden');
  10192. }
  10193. function openEditRoutingFilterModal(id) {
  10194. const r = (state.routingFilters || []).find(item => item.id === id);
  10195. if (!r) return;
  10196. const idEl = document.getElementById('modal-rf-id');
  10197. if (idEl) idEl.value = r.id;
  10198. const titleEl = document.getElementById('modal-rf-title');
  10199. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10200. const chainEl = document.getElementById('modal-rf-chain');
  10201. if (chainEl) chainEl.value = r.chain || '';
  10202. const orderEl = document.getElementById('modal-rf-order');
  10203. if (orderEl) orderEl.value = r.rule_order || 10;
  10204. const ruleEl = document.getElementById('modal-rf-rule');
  10205. if (ruleEl) {
  10206. if (r.rule) {
  10207. ruleEl.value = r.rule;
  10208. } else {
  10209. let conds = [];
  10210. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10211. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10212. let act = r.action || 'accept';
  10213. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10214. }
  10215. }
  10216. const comEl = document.getElementById('modal-rf-comment');
  10217. if (comEl) comEl.value = r.comment || '';
  10218. const disEl = document.getElementById('modal-rf-disabled');
  10219. if (disEl) disEl.checked = !!r.disabled;
  10220. const modal = document.getElementById('modal-routing-filter');
  10221. if (modal) modal.classList.remove('hidden');
  10222. }
  10223. function closeRoutingFilterModal() {
  10224. const modal = document.getElementById('modal-routing-filter');
  10225. if (modal) modal.classList.add('hidden');
  10226. }
  10227. async function submitRoutingFilter(e) {
  10228. if (e) e.preventDefault();
  10229. const payload = {
  10230. id: document.getElementById('modal-rf-id').value,
  10231. chain: document.getElementById('modal-rf-chain').value.trim(),
  10232. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10233. rule: document.getElementById('modal-rf-rule').value.trim(),
  10234. comment: document.getElementById('modal-rf-comment').value.trim(),
  10235. disabled: document.getElementById('modal-rf-disabled').checked
  10236. };
  10237. try {
  10238. const res = await fetch(`${API_BASE}/routing/filters`, {
  10239. method: 'POST',
  10240. headers: { 'Content-Type': 'application/json' },
  10241. body: JSON.stringify(payload)
  10242. });
  10243. if (res.ok) {
  10244. closeRoutingFilterModal();
  10245. showToast('Success', 'Routing filter rule saved', 'success');
  10246. loadDynamicRouting();
  10247. } else {
  10248. const err = await res.json();
  10249. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10250. }
  10251. } catch (err) {
  10252. showToast('Error', err.message, 'error');
  10253. }
  10254. }
  10255. async function applyRoutingFilterForm() {
  10256. const payload = {
  10257. id: document.getElementById('modal-rf-id').value,
  10258. chain: document.getElementById('modal-rf-chain').value.trim(),
  10259. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10260. rule: document.getElementById('modal-rf-rule').value.trim(),
  10261. comment: document.getElementById('modal-rf-comment').value.trim(),
  10262. disabled: document.getElementById('modal-rf-disabled').checked
  10263. };
  10264. try {
  10265. const res = await fetch(`${API_BASE}/routing/filters`, {
  10266. method: 'POST',
  10267. headers: { 'Content-Type': 'application/json' },
  10268. body: JSON.stringify(payload)
  10269. });
  10270. if (res.ok) {
  10271. const data = await res.json();
  10272. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10273. showToast('Applied', 'Routing filter configuration applied', 'success');
  10274. loadDynamicRouting();
  10275. } else {
  10276. const err = await res.json();
  10277. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10278. }
  10279. } catch (err) {
  10280. showToast('Error', err.message, 'error');
  10281. }
  10282. }
  10283. async function moveRoutingFilterOrder(id, delta) {
  10284. const list = state.routingFilters || [];
  10285. const idx = list.findIndex(r => r.id === id);
  10286. if (idx < 0) return;
  10287. const targetIdx = idx + delta;
  10288. if (targetIdx < 0 || targetIdx >= list.length) return;
  10289. const currentOrder = list[idx].rule_order || 10;
  10290. const targetOrder = list[targetIdx].rule_order || 20;
  10291. list[idx].rule_order = targetOrder;
  10292. list[targetIdx].rule_order = currentOrder;
  10293. try {
  10294. await fetch(`${API_BASE}/routing/filters`, {
  10295. method: 'POST',
  10296. headers: { 'Content-Type': 'application/json' },
  10297. body: JSON.stringify(list[idx])
  10298. });
  10299. await fetch(`${API_BASE}/routing/filters`, {
  10300. method: 'POST',
  10301. headers: { 'Content-Type': 'application/json' },
  10302. body: JSON.stringify(list[targetIdx])
  10303. });
  10304. loadDynamicRouting();
  10305. } catch (e) {
  10306. console.error('Reorder error:', e);
  10307. }
  10308. }
  10309. async function deleteRoutingFilter(id) {
  10310. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10311. try {
  10312. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10313. if (res.ok) {
  10314. showToast('Deleted', 'Routing filter rule removed', 'info');
  10315. loadDynamicRouting();
  10316. } else {
  10317. const err = await res.json();
  10318. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10319. }
  10320. } catch (err) {
  10321. showToast('Error', err.message, 'error');
  10322. }
  10323. }
  10324. async function toggleRoutingFilterState(id, disabled) {
  10325. try {
  10326. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10327. method: 'POST',
  10328. headers: { 'Content-Type': 'application/json' },
  10329. body: JSON.stringify({ disabled })
  10330. });
  10331. if (res.ok) {
  10332. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10333. loadDynamicRouting();
  10334. } else {
  10335. const err = await res.json();
  10336. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10337. }
  10338. } catch (err) {
  10339. showToast('Error', err.message, 'error');
  10340. }
  10341. }
  10342. // -------------------------------------------------------------
  10343. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10344. // -------------------------------------------------------------
  10345. function openAddSelectRuleModal() {
  10346. document.getElementById('modal-rf-sr-id').value = '';
  10347. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10348. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10349. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10350. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10351. document.getElementById('modal-rf-sr-comment').value = '';
  10352. document.getElementById('modal-rf-sr-disabled').checked = false;
  10353. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10354. }
  10355. function openEditSelectRuleModal(id) {
  10356. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10357. if (!r) return;
  10358. document.getElementById('modal-rf-sr-id').value = r.id;
  10359. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10360. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10361. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10362. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10363. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10364. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10365. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10366. }
  10367. function closeSelectRuleModal() {
  10368. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10369. }
  10370. async function submitSelectRule(e) {
  10371. e.preventDefault();
  10372. const payload = {
  10373. id: document.getElementById('modal-rf-sr-id').value,
  10374. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10375. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10376. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10377. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10378. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10379. };
  10380. try {
  10381. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10382. method: 'POST',
  10383. headers: { 'Content-Type': 'application/json' },
  10384. body: JSON.stringify(payload)
  10385. });
  10386. if (res.ok) {
  10387. closeSelectRuleModal();
  10388. showToast('Success', 'Select rule saved', 'success');
  10389. loadDynamicRouting();
  10390. } else {
  10391. const err = await res.json();
  10392. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10393. }
  10394. } catch (err) {
  10395. showToast('Error', err.message, 'error');
  10396. }
  10397. }
  10398. async function deleteSelectRule(id) {
  10399. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10400. try {
  10401. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10402. if (res.ok) {
  10403. showToast('Deleted', 'Select rule removed', 'info');
  10404. loadDynamicRouting();
  10405. } else {
  10406. const err = await res.json();
  10407. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10408. }
  10409. } catch (err) {
  10410. showToast('Error', err.message, 'error');
  10411. }
  10412. }
  10413. async function toggleSelectRuleState(id, disabled) {
  10414. try {
  10415. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10416. method: 'POST',
  10417. headers: { 'Content-Type': 'application/json' },
  10418. body: JSON.stringify({ disabled })
  10419. });
  10420. if (res.ok) {
  10421. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10422. loadDynamicRouting();
  10423. } else {
  10424. const err = await res.json();
  10425. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10426. }
  10427. } catch (err) {
  10428. showToast('Error', err.message, 'error');
  10429. }
  10430. }
  10431. // -------------------------------------------------------------
  10432. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10433. // -------------------------------------------------------------
  10434. function openAddCommunityListModal() {
  10435. document.getElementById('modal-rf-cl-id').value = '';
  10436. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10437. document.getElementById('modal-rf-cl-name').value = '';
  10438. document.getElementById('modal-rf-cl-communities').value = '';
  10439. document.getElementById('modal-rf-cl-regexp').value = '';
  10440. document.getElementById('modal-rf-cl-comment').value = '';
  10441. document.getElementById('modal-rf-cl-disabled').checked = false;
  10442. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10443. }
  10444. function openEditCommunityListModal(id) {
  10445. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10446. if (!cl) return;
  10447. document.getElementById('modal-rf-cl-id').value = cl.id;
  10448. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10449. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10450. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10451. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10452. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10453. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10454. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10455. }
  10456. function closeCommunityListModal() {
  10457. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10458. }
  10459. async function submitCommunityList(e) {
  10460. e.preventDefault();
  10461. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10462. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10463. const payload = {
  10464. id: document.getElementById('modal-rf-cl-id').value,
  10465. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10466. communities: comms,
  10467. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10468. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10469. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10470. };
  10471. try {
  10472. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10473. method: 'POST',
  10474. headers: { 'Content-Type': 'application/json' },
  10475. body: JSON.stringify(payload)
  10476. });
  10477. if (res.ok) {
  10478. closeCommunityListModal();
  10479. showToast('Success', 'Community list saved', 'success');
  10480. loadDynamicRouting();
  10481. } else {
  10482. const err = await res.json();
  10483. showToast('Error', err.error || 'Failed to save community list', 'error');
  10484. }
  10485. } catch (err) {
  10486. showToast('Error', err.message, 'error');
  10487. }
  10488. }
  10489. async function deleteCommunityList(id) {
  10490. if (!confirm('Are you sure you want to delete this community list?')) return;
  10491. try {
  10492. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10493. if (res.ok) {
  10494. showToast('Deleted', 'Community list removed', 'info');
  10495. loadDynamicRouting();
  10496. } else {
  10497. const err = await res.json();
  10498. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10499. }
  10500. } catch (err) {
  10501. showToast('Error', err.message, 'error');
  10502. }
  10503. }
  10504. async function toggleCommunityListState(id, disabled) {
  10505. try {
  10506. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10507. method: 'POST',
  10508. headers: { 'Content-Type': 'application/json' },
  10509. body: JSON.stringify({ disabled })
  10510. });
  10511. if (res.ok) {
  10512. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10513. loadDynamicRouting();
  10514. } else {
  10515. const err = await res.json();
  10516. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10517. }
  10518. } catch (err) {
  10519. showToast('Error', err.message, 'error');
  10520. }
  10521. }
  10522. // -------------------------------------------------------------
  10523. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10524. // -------------------------------------------------------------
  10525. function openAddASListModal() {
  10526. document.getElementById('modal-rf-al-id').value = '';
  10527. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10528. document.getElementById('modal-rf-al-name').value = '';
  10529. document.getElementById('modal-rf-al-range').value = '';
  10530. document.getElementById('modal-rf-al-comment').value = '';
  10531. document.getElementById('modal-rf-al-disabled').checked = false;
  10532. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10533. }
  10534. function openEditASListModal(id) {
  10535. const al = (state.routingASLists || []).find(item => item.id === id);
  10536. if (!al) return;
  10537. document.getElementById('modal-rf-al-id').value = al.id;
  10538. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10539. document.getElementById('modal-rf-al-name').value = al.name || '';
  10540. document.getElementById('modal-rf-al-range').value = al.range || '';
  10541. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10542. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10543. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10544. }
  10545. function closeASListModal() {
  10546. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10547. }
  10548. async function submitASList(e) {
  10549. e.preventDefault();
  10550. const payload = {
  10551. id: document.getElementById('modal-rf-al-id').value,
  10552. name: document.getElementById('modal-rf-al-name').value.trim(),
  10553. range: document.getElementById('modal-rf-al-range').value.trim(),
  10554. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10555. disabled: document.getElementById('modal-rf-al-disabled').checked
  10556. };
  10557. try {
  10558. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10559. method: 'POST',
  10560. headers: { 'Content-Type': 'application/json' },
  10561. body: JSON.stringify(payload)
  10562. });
  10563. if (res.ok) {
  10564. closeASListModal();
  10565. showToast('Success', 'AS number list saved', 'success');
  10566. loadDynamicRouting();
  10567. } else {
  10568. const err = await res.json();
  10569. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10570. }
  10571. } catch (err) {
  10572. showToast('Error', err.message, 'error');
  10573. }
  10574. }
  10575. async function deleteASList(id) {
  10576. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10577. try {
  10578. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10579. if (res.ok) {
  10580. showToast('Deleted', 'AS list removed', 'info');
  10581. loadDynamicRouting();
  10582. } else {
  10583. const err = await res.json();
  10584. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10585. }
  10586. } catch (err) {
  10587. showToast('Error', err.message, 'error');
  10588. }
  10589. }
  10590. async function toggleASListState(id, disabled) {
  10591. try {
  10592. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10593. method: 'POST',
  10594. headers: { 'Content-Type': 'application/json' },
  10595. body: JSON.stringify({ disabled })
  10596. });
  10597. if (res.ok) {
  10598. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10599. loadDynamicRouting();
  10600. } else {
  10601. const err = await res.json();
  10602. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10603. }
  10604. } catch (err) {
  10605. showToast('Error', err.message, 'error');
  10606. }
  10607. }
  10608. // ==========================================
  10609. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10610. // ==========================================
  10611. function loadToolsView() {
  10612. populateToolsInterfaces();
  10613. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10614. }
  10615. function populateToolsInterfaces() {
  10616. const pingSel = document.getElementById('tools-ping-iface');
  10617. const traceSel = document.getElementById('tools-tr-iface');
  10618. let opts = '<option value="">Auto (Default Route)</option>';
  10619. if (Array.isArray(state.interfaces)) {
  10620. state.interfaces.forEach(iface => {
  10621. if (iface.name) {
  10622. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10623. }
  10624. });
  10625. }
  10626. if (pingSel) {
  10627. const cur = pingSel.value;
  10628. pingSel.innerHTML = opts;
  10629. if (cur) pingSel.value = cur;
  10630. }
  10631. if (traceSel) {
  10632. const cur = traceSel.value;
  10633. traceSel.innerHTML = opts;
  10634. if (cur) traceSel.value = cur;
  10635. }
  10636. }
  10637. function switchToolsSubTab(subTab) {
  10638. state.activeToolsSubTab = subTab;
  10639. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10640. tabs.forEach(t => {
  10641. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10642. const view = document.getElementById(`tools-view-${t}`);
  10643. if (btn) {
  10644. if (t === subTab) {
  10645. 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';
  10646. } else {
  10647. 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';
  10648. }
  10649. }
  10650. if (view) {
  10651. if (t === subTab) {
  10652. view.classList.remove('hidden');
  10653. } else {
  10654. view.classList.add('hidden');
  10655. }
  10656. }
  10657. });
  10658. }
  10659. function setPortPreset(port) {
  10660. const input = document.getElementById('tools-port-num');
  10661. if (input) input.value = port;
  10662. }
  10663. let pingAbortController = null;
  10664. let tracerouteAbortController = null;
  10665. function clearPingTable() {
  10666. const tbody = document.getElementById('tools-ping-tbody');
  10667. if (tbody) tbody.innerHTML = '';
  10668. const rawEl = document.getElementById('tools-ping-raw');
  10669. if (rawEl) rawEl.innerText = '';
  10670. const sentEl = document.getElementById('tools-ping-stat-sent');
  10671. if (sentEl) sentEl.innerText = '0';
  10672. const recvEl = document.getElementById('tools-ping-stat-recv');
  10673. if (recvEl) recvEl.innerText = '0';
  10674. const lossEl = document.getElementById('tools-ping-stat-loss');
  10675. if (lossEl) lossEl.innerText = '0%';
  10676. const avgEl = document.getElementById('tools-ping-stat-avg');
  10677. if (avgEl) avgEl.innerText = '0 ms';
  10678. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10679. if (minMaxEl) minMaxEl.innerText = '-';
  10680. const badge = document.getElementById('tools-ping-status-badge');
  10681. if (badge) {
  10682. badge.className = '';
  10683. badge.innerText = '';
  10684. }
  10685. }
  10686. function clearTracerouteTable() {
  10687. const tbody = document.getElementById('tools-tr-tbody');
  10688. if (tbody) tbody.innerHTML = '';
  10689. const rawEl = document.getElementById('tools-tr-raw');
  10690. if (rawEl) rawEl.innerText = '';
  10691. const statHops = document.getElementById('tools-tr-hops-count');
  10692. if (statHops) statHops.innerText = '0 Hops';
  10693. }
  10694. function resetPingButton() {
  10695. const btn = document.getElementById('tools-ping-btn');
  10696. const btnText = document.getElementById('tools-ping-btn-text');
  10697. const spinner = document.getElementById('tools-ping-spinner');
  10698. if (btn) {
  10699. btn.disabled = false;
  10700. 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';
  10701. }
  10702. if (btnText) btnText.innerText = 'Start Ping';
  10703. if (spinner) spinner.classList.add('hidden');
  10704. }
  10705. function setPingRunningButton() {
  10706. const btn = document.getElementById('tools-ping-btn');
  10707. const btnText = document.getElementById('tools-ping-btn-text');
  10708. const spinner = document.getElementById('tools-ping-spinner');
  10709. if (btn) {
  10710. btn.disabled = false;
  10711. 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';
  10712. }
  10713. if (btnText) btnText.innerText = 'Stop Ping';
  10714. if (spinner) spinner.classList.remove('hidden');
  10715. }
  10716. function resetTracerouteButton() {
  10717. const btn = document.getElementById('tools-tr-btn');
  10718. const btnText = document.getElementById('tools-tr-btn-text');
  10719. const spinner = document.getElementById('tools-tr-spinner');
  10720. if (btn) {
  10721. btn.disabled = false;
  10722. 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';
  10723. }
  10724. if (btnText) btnText.innerText = 'Start Traceroute';
  10725. if (spinner) spinner.classList.add('hidden');
  10726. }
  10727. function setTracerouteRunningButton() {
  10728. const btn = document.getElementById('tools-tr-btn');
  10729. const btnText = document.getElementById('tools-tr-btn-text');
  10730. const spinner = document.getElementById('tools-tr-spinner');
  10731. if (btn) {
  10732. btn.disabled = false;
  10733. 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';
  10734. }
  10735. if (btnText) btnText.innerText = 'Stop Traceroute';
  10736. if (spinner) spinner.classList.remove('hidden');
  10737. }
  10738. async function executePing(e) {
  10739. if (e) e.preventDefault();
  10740. // If already running, clicking the button stops the stream!
  10741. if (pingAbortController) {
  10742. pingAbortController.abort();
  10743. pingAbortController = null;
  10744. resetPingButton();
  10745. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10746. return;
  10747. }
  10748. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10749. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10750. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10751. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10752. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10753. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10754. if (!target) {
  10755. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10756. return;
  10757. }
  10758. clearPingTable();
  10759. const resCard = document.getElementById('tools-ping-results');
  10760. if (resCard) resCard.classList.remove('hidden');
  10761. pingAbortController = new AbortController();
  10762. setPingRunningButton();
  10763. try {
  10764. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10765. method: 'POST',
  10766. headers: { 'Content-Type': 'application/json' },
  10767. body: JSON.stringify({
  10768. target,
  10769. count,
  10770. size,
  10771. timeout,
  10772. interface: iface,
  10773. dont_frag: dontFrag
  10774. }),
  10775. signal: pingAbortController.signal
  10776. });
  10777. if (!res.ok) {
  10778. const errText = await res.text();
  10779. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10780. resetPingButton();
  10781. pingAbortController = null;
  10782. return;
  10783. }
  10784. const reader = res.body.getReader();
  10785. const decoder = new TextDecoder('utf-8');
  10786. let buffer = '';
  10787. while (true) {
  10788. const { done, value } = await reader.read();
  10789. if (done) break;
  10790. buffer += decoder.decode(value, { stream: true });
  10791. const blocks = buffer.split('\n\n');
  10792. buffer = blocks.pop() || '';
  10793. for (const block of blocks) {
  10794. const trimmed = block.trim();
  10795. if (!trimmed) continue;
  10796. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10797. try {
  10798. const evt = JSON.parse(line);
  10799. handleLivePingEvent(evt);
  10800. } catch (parseErr) {
  10801. console.warn('Ping SSE parse error:', parseErr, line);
  10802. }
  10803. }
  10804. }
  10805. } catch (err) {
  10806. if (err.name === 'AbortError') {
  10807. // User aborted normally
  10808. } else {
  10809. showToast('Ping Error', err.message, 'error');
  10810. }
  10811. } finally {
  10812. pingAbortController = null;
  10813. resetPingButton();
  10814. }
  10815. }
  10816. function handleLivePingEvent(evt) {
  10817. const sentEl = document.getElementById('tools-ping-stat-sent');
  10818. const recvEl = document.getElementById('tools-ping-stat-recv');
  10819. const lossEl = document.getElementById('tools-ping-stat-loss');
  10820. const avgEl = document.getElementById('tools-ping-stat-avg');
  10821. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10822. const badge = document.getElementById('tools-ping-status-badge');
  10823. const tbody = document.getElementById('tools-ping-tbody');
  10824. const rawEl = document.getElementById('tools-ping-raw');
  10825. if (evt.raw && rawEl) {
  10826. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10827. rawEl.scrollTop = rawEl.scrollHeight;
  10828. }
  10829. if (evt.type === 'reply') {
  10830. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10831. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10832. if (lossEl && evt.packet_loss_pct !== undefined) {
  10833. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10834. lossEl.className = evt.packet_loss_pct === 0
  10835. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10836. : (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');
  10837. }
  10838. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10839. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10840. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10841. }
  10842. if (badge) {
  10843. if (evt.packet_loss_pct === 0) {
  10844. 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';
  10845. badge.innerText = '100% OK';
  10846. } else {
  10847. 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';
  10848. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10849. }
  10850. }
  10851. if (tbody) {
  10852. const tr = document.createElement('tr');
  10853. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10854. tr.innerHTML = `
  10855. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10856. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10857. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10858. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10859. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10860. <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>
  10861. `;
  10862. tbody.appendChild(tr);
  10863. }
  10864. } else if (evt.type === 'timeout') {
  10865. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10866. if (lossEl && evt.packet_loss_pct !== undefined) {
  10867. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10868. 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';
  10869. }
  10870. if (badge) {
  10871. 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';
  10872. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10873. }
  10874. if (tbody) {
  10875. const tr = document.createElement('tr');
  10876. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10877. tr.innerHTML = `
  10878. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10879. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10880. <td class="py-2 px-3 text-slate-600">--</td>
  10881. <td class="py-2 px-3 text-slate-600">--</td>
  10882. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10883. <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>
  10884. `;
  10885. tbody.appendChild(tr);
  10886. }
  10887. } else if (evt.type === 'unreach') {
  10888. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10889. if (lossEl && evt.packet_loss_pct !== undefined) {
  10890. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10891. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10892. }
  10893. if (badge) {
  10894. 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';
  10895. badge.innerText = 'UNREACHABLE';
  10896. }
  10897. if (tbody) {
  10898. const tr = document.createElement('tr');
  10899. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10900. tr.innerHTML = `
  10901. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10902. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10903. <td class="py-2 px-3 text-slate-600">--</td>
  10904. <td class="py-2 px-3 text-slate-600">--</td>
  10905. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10906. <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>
  10907. `;
  10908. tbody.appendChild(tr);
  10909. }
  10910. } else if (evt.type === 'stats') {
  10911. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10912. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10913. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10914. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10915. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10916. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10917. }
  10918. } else if (evt.type === 'done') {
  10919. 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');
  10920. }
  10921. }
  10922. async function executeTraceroute(e) {
  10923. if (e) e.preventDefault();
  10924. if (tracerouteAbortController) {
  10925. tracerouteAbortController.abort();
  10926. tracerouteAbortController = null;
  10927. resetTracerouteButton();
  10928. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10929. return;
  10930. }
  10931. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10932. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10933. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10934. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10935. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10936. if (!target) {
  10937. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10938. return;
  10939. }
  10940. clearTracerouteTable();
  10941. const resCard = document.getElementById('tools-tr-results');
  10942. if (resCard) resCard.classList.remove('hidden');
  10943. tracerouteAbortController = new AbortController();
  10944. setTracerouteRunningButton();
  10945. try {
  10946. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10947. method: 'POST',
  10948. headers: { 'Content-Type': 'application/json' },
  10949. body: JSON.stringify({
  10950. target,
  10951. max_hops: maxHops,
  10952. protocol,
  10953. interface: iface,
  10954. resolve
  10955. }),
  10956. signal: tracerouteAbortController.signal
  10957. });
  10958. if (!res.ok) {
  10959. const errText = await res.text();
  10960. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10961. resetTracerouteButton();
  10962. tracerouteAbortController = null;
  10963. return;
  10964. }
  10965. const reader = res.body.getReader();
  10966. const decoder = new TextDecoder('utf-8');
  10967. let buffer = '';
  10968. while (true) {
  10969. const { done, value } = await reader.read();
  10970. if (done) break;
  10971. buffer += decoder.decode(value, { stream: true });
  10972. const blocks = buffer.split('\n\n');
  10973. buffer = blocks.pop() || '';
  10974. for (const block of blocks) {
  10975. const trimmed = block.trim();
  10976. if (!trimmed) continue;
  10977. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10978. try {
  10979. const evt = JSON.parse(line);
  10980. handleLiveTracerouteEvent(evt);
  10981. } catch (parseErr) {
  10982. console.warn('Traceroute SSE parse error:', parseErr, line);
  10983. }
  10984. }
  10985. }
  10986. } catch (err) {
  10987. if (err.name === 'AbortError') {
  10988. // User aborted normally
  10989. } else {
  10990. showToast('Traceroute Error', err.message, 'error');
  10991. }
  10992. } finally {
  10993. tracerouteAbortController = null;
  10994. resetTracerouteButton();
  10995. }
  10996. }
  10997. function handleLiveTracerouteEvent(evt) {
  10998. const statHops = document.getElementById('tools-tr-hops-count');
  10999. const tbody = document.getElementById('tools-tr-tbody');
  11000. const rawEl = document.getElementById('tools-tr-raw');
  11001. if (evt.raw && rawEl) {
  11002. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11003. rawEl.scrollTop = rawEl.scrollHeight;
  11004. }
  11005. if (evt.hops_count !== undefined && statHops) {
  11006. statHops.innerText = `${evt.hops_count} Hops`;
  11007. }
  11008. if (evt.type === 'hop' && evt.hop && tbody) {
  11009. const h = evt.hop;
  11010. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11011. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11012. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11013. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11014. const tr = document.createElement('tr');
  11015. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11016. tr.innerHTML = `
  11017. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11018. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11019. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11020. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11021. <td class="py-2.5 px-3 text-right">
  11022. ${isTimeout
  11023. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11024. : '<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>'}
  11025. </td>
  11026. `;
  11027. tbody.appendChild(tr);
  11028. } else if (evt.type === 'done') {
  11029. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11030. }
  11031. }
  11032. async function executeMTR(e) {
  11033. if (e) e.preventDefault();
  11034. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11035. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11036. if (!target) {
  11037. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11038. return;
  11039. }
  11040. const btn = document.getElementById('tools-mtr-btn');
  11041. const spinner = document.getElementById('tools-mtr-spinner');
  11042. if (btn) btn.disabled = true;
  11043. if (spinner) spinner.classList.remove('hidden');
  11044. try {
  11045. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11046. method: 'POST',
  11047. headers: { 'Content-Type': 'application/json' },
  11048. body: JSON.stringify({ target, count: cycles })
  11049. });
  11050. const data = await res.json();
  11051. if (!res.ok) {
  11052. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11053. return;
  11054. }
  11055. const resCard = document.getElementById('tools-mtr-results');
  11056. if (resCard) resCard.classList.remove('hidden');
  11057. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11058. const statHops = document.getElementById('tools-mtr-hops-count');
  11059. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11060. const tbody = document.getElementById('tools-mtr-tbody');
  11061. if (tbody) {
  11062. if (hopsCount > 0) {
  11063. tbody.innerHTML = data.hops.map(h => {
  11064. 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');
  11065. return `
  11066. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11067. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11068. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11069. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11070. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11071. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11072. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11073. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11074. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11075. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11076. </tr>
  11077. `;
  11078. }).join('');
  11079. } else {
  11080. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11081. }
  11082. }
  11083. const rawEl = document.getElementById('tools-mtr-raw');
  11084. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11085. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11086. } catch (err) {
  11087. showToast('MTR Error', err.message, 'error');
  11088. } finally {
  11089. if (btn) btn.disabled = false;
  11090. if (spinner) spinner.classList.add('hidden');
  11091. }
  11092. }
  11093. async function executeDNS(e) {
  11094. if (e) e.preventDefault();
  11095. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11096. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11097. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11098. if (!domain) {
  11099. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11100. return;
  11101. }
  11102. const btn = document.getElementById('tools-dns-btn');
  11103. const spinner = document.getElementById('tools-dns-spinner');
  11104. if (btn) btn.disabled = true;
  11105. if (spinner) spinner.classList.remove('hidden');
  11106. try {
  11107. const res = await fetch(`${API_BASE}/tools/dns`, {
  11108. method: 'POST',
  11109. headers: { 'Content-Type': 'application/json' },
  11110. body: JSON.stringify({ domain, type, server })
  11111. });
  11112. const data = await res.json();
  11113. if (!res.ok) {
  11114. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11115. return;
  11116. }
  11117. const resCard = document.getElementById('tools-dns-results');
  11118. if (resCard) resCard.classList.remove('hidden');
  11119. const metaEl = document.getElementById('tools-dns-meta');
  11120. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11121. const tbody = document.getElementById('tools-dns-tbody');
  11122. if (tbody) {
  11123. if (Array.isArray(data.records) && data.records.length > 0) {
  11124. tbody.innerHTML = data.records.map(r => `
  11125. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11126. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11127. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11128. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11129. <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>
  11130. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11131. </tr>
  11132. `).join('');
  11133. } else {
  11134. 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>`;
  11135. }
  11136. }
  11137. const rawEl = document.getElementById('tools-dns-raw');
  11138. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11139. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11140. } catch (err) {
  11141. showToast('DNS Error', err.message, 'error');
  11142. } finally {
  11143. if (btn) btn.disabled = false;
  11144. if (spinner) spinner.classList.add('hidden');
  11145. }
  11146. }
  11147. async function executePortProbe(e) {
  11148. if (e) e.preventDefault();
  11149. const target = document.getElementById('tools-port-target')?.value?.trim();
  11150. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11151. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11152. if (!target || !port) {
  11153. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11154. return;
  11155. }
  11156. const btn = document.getElementById('tools-port-btn');
  11157. const spinner = document.getElementById('tools-port-spinner');
  11158. if (btn) btn.disabled = true;
  11159. if (spinner) spinner.classList.remove('hidden');
  11160. try {
  11161. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11162. method: 'POST',
  11163. headers: { 'Content-Type': 'application/json' },
  11164. body: JSON.stringify({ target, port, timeout })
  11165. });
  11166. const data = await res.json();
  11167. if (!res.ok) {
  11168. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11169. return;
  11170. }
  11171. const resCard = document.getElementById('tools-port-results');
  11172. if (resCard) resCard.classList.remove('hidden');
  11173. const banner = document.getElementById('tools-port-banner');
  11174. const icon = document.getElementById('tools-port-icon');
  11175. const title = document.getElementById('tools-port-title');
  11176. const sub = document.getElementById('tools-port-sub');
  11177. const latency = document.getElementById('tools-port-latency');
  11178. if (data.open) {
  11179. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11180. if (icon) {
  11181. 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';
  11182. icon.innerText = '✓';
  11183. }
  11184. if (title) {
  11185. title.className = 'text-sm font-bold text-emerald-300';
  11186. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11187. }
  11188. if (sub) {
  11189. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11190. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11191. }
  11192. if (latency) {
  11193. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11194. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11195. }
  11196. } else {
  11197. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11198. if (icon) {
  11199. 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';
  11200. icon.innerText = '✕';
  11201. }
  11202. if (title) {
  11203. title.className = 'text-sm font-bold text-rose-300';
  11204. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11205. }
  11206. if (sub) {
  11207. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11208. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11209. }
  11210. if (latency) {
  11211. latency.className = 'text-base font-bold font-mono text-slate-500';
  11212. latency.innerText = '--';
  11213. }
  11214. }
  11215. const rawEl = document.getElementById('tools-port-raw');
  11216. 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'}`);
  11217. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11218. } catch (err) {
  11219. showToast('Probe Error', err.message, 'error');
  11220. } finally {
  11221. if (btn) btn.disabled = false;
  11222. if (spinner) spinner.classList.add('hidden');
  11223. }
  11224. }
  11225. // ==========================================
  11226. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11227. // ==========================================
  11228. async function loadDHCPClients(showToastMsg = false) {
  11229. try {
  11230. const [clientsRes, sumRes] = await Promise.all([
  11231. fetch(`${API_BASE}/dhcp/clients`),
  11232. fetch(`${API_BASE}/dhcp/clients/summary`)
  11233. ]);
  11234. if (clientsRes.ok) {
  11235. state.dhcpClients = await clientsRes.json();
  11236. }
  11237. if (sumRes.ok) {
  11238. state.dhcpSummary = await sumRes.json();
  11239. }
  11240. renderDHCPClients();
  11241. updateDHCPSummaryCards();
  11242. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11243. if (bDhcp && state.dhcpSummary) {
  11244. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11245. }
  11246. if (showToastMsg) {
  11247. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11248. }
  11249. } catch (err) {
  11250. console.error('Failed to load DHCP clients:', err);
  11251. if (showToastMsg) {
  11252. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11253. }
  11254. }
  11255. }
  11256. function updateDHCPSummaryCards() {
  11257. const sum = state.dhcpSummary || {
  11258. total_clients: (state.dhcpClients || []).length,
  11259. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11260. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11261. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11262. };
  11263. const totalEl = document.getElementById('dhcp-stat-total');
  11264. const boundEl = document.getElementById('dhcp-stat-bound');
  11265. const searchEl = document.getElementById('dhcp-stat-searching');
  11266. const disEl = document.getElementById('dhcp-stat-disabled');
  11267. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11268. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11269. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11270. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11271. }
  11272. function renderDHCPClients() {
  11273. const tbody = document.getElementById('dhcp-clients-tbody');
  11274. const emptyState = document.getElementById('dhcp-clients-empty');
  11275. if (!tbody) return;
  11276. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11277. if (clients.length === 0) {
  11278. tbody.innerHTML = '';
  11279. if (emptyState) emptyState.classList.remove('hidden');
  11280. return;
  11281. }
  11282. if (emptyState) emptyState.classList.add('hidden');
  11283. tbody.innerHTML = clients.map(c => {
  11284. let statusBadge = '';
  11285. if (!c.enabled) {
  11286. 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>';
  11287. } else if (c.status === 'bound') {
  11288. 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>';
  11289. } else if (c.status === 'searching') {
  11290. 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>';
  11291. } else if (c.status === 'stopped') {
  11292. 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>';
  11293. } else {
  11294. 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>`;
  11295. }
  11296. 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>';
  11297. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11298. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11299. 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>';
  11300. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11301. // Option flags
  11302. const flags = [];
  11303. 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>');
  11304. 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>');
  11305. 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>');
  11306. 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>`);
  11307. return `
  11308. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11309. <td class="py-3 px-4">
  11310. <div class="flex items-center gap-2">
  11311. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11312. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11313. </div>
  11314. </td>
  11315. <td class="py-3 px-4">${statusBadge}</td>
  11316. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11317. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11318. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11319. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11320. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11321. <td class="py-3 px-4">
  11322. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11323. </td>
  11324. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11325. ${c.enabled ? `
  11326. <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>
  11327. <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>
  11328. <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>
  11329. ` : `
  11330. <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>
  11331. `}
  11332. <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>
  11333. <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>
  11334. </td>
  11335. </tr>
  11336. `;
  11337. }).join('');
  11338. }
  11339. function openDHCPClientModal(clientId = null) {
  11340. const modal = document.getElementById('modal-dhcp-client');
  11341. if (!modal) return;
  11342. const title = document.getElementById('modal-dhcp-title');
  11343. const idInput = document.getElementById('modal-dhcp-id');
  11344. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11345. const distInput = document.getElementById('modal-dhcp-distance');
  11346. const commentInput = document.getElementById('modal-dhcp-comment');
  11347. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11348. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11349. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11350. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11351. // Populate interfaces
  11352. if (ifaceSelect) {
  11353. let opts = '<option value="">Select interface...</option>';
  11354. const allIfaces = state.interfaces || [];
  11355. const allVlans = state.vlans || [];
  11356. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11357. // Group 1: Physical & Bridge Interfaces
  11358. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11359. allIfaces.forEach(i => {
  11360. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11361. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11362. });
  11363. opts += '</optgroup>';
  11364. // Group 2: VLAN Interfaces
  11365. if (allVlans.length > 0) {
  11366. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11367. allVlans.forEach(v => {
  11368. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11369. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11370. });
  11371. opts += '</optgroup>';
  11372. }
  11373. ifaceSelect.innerHTML = opts;
  11374. }
  11375. if (clientId) {
  11376. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11377. if (client) {
  11378. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11379. if (idInput) idInput.value = client.id;
  11380. if (ifaceSelect) {
  11381. ifaceSelect.value = client.interface;
  11382. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11383. }
  11384. if (distInput) distInput.value = client.default_route_distance || 1;
  11385. if (commentInput) commentInput.value = client.comment || '';
  11386. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11387. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11388. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11389. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11390. }
  11391. } else {
  11392. if (title) title.innerText = 'Add DHCP Client';
  11393. if (idInput) idInput.value = '';
  11394. if (ifaceSelect) {
  11395. ifaceSelect.value = '';
  11396. ifaceSelect.disabled = false;
  11397. }
  11398. if (distInput) distInput.value = 1;
  11399. if (commentInput) commentInput.value = '';
  11400. if (defRouteCheck) defRouteCheck.checked = true;
  11401. if (peerDnsCheck) peerDnsCheck.checked = true;
  11402. if (peerNtpCheck) peerNtpCheck.checked = true;
  11403. if (enabledCheck) enabledCheck.checked = true;
  11404. }
  11405. modal.classList.remove('hidden');
  11406. }
  11407. function openDHCPClientModalForIface(ifaceName) {
  11408. openDHCPClientModal();
  11409. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11410. if (ifaceSelect && ifaceName) {
  11411. ifaceSelect.value = ifaceName;
  11412. }
  11413. }
  11414. function closeDHCPClientModal() {
  11415. const modal = document.getElementById('modal-dhcp-client');
  11416. if (modal) modal.classList.add('hidden');
  11417. }
  11418. async function submitSaveDHCPClient(e) {
  11419. if (e) e.preventDefault();
  11420. const id = document.getElementById('modal-dhcp-id')?.value;
  11421. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11422. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11423. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11424. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11425. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11426. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11427. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11428. if (!id && !iface) {
  11429. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11430. return;
  11431. }
  11432. try {
  11433. let res;
  11434. if (id) {
  11435. // PUT update
  11436. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11437. method: 'PUT',
  11438. headers: { 'Content-Type': 'application/json' },
  11439. body: JSON.stringify({
  11440. enabled,
  11441. add_default_route: defRoute,
  11442. default_route_distance: distance,
  11443. use_peer_dns: peerDns,
  11444. use_peer_ntp: peerNtp,
  11445. comment
  11446. })
  11447. });
  11448. } else {
  11449. // POST create
  11450. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11451. method: 'POST',
  11452. headers: { 'Content-Type': 'application/json' },
  11453. body: JSON.stringify({
  11454. interface: iface,
  11455. enabled,
  11456. add_default_route: defRoute,
  11457. default_route_distance: distance,
  11458. use_peer_dns: peerDns,
  11459. use_peer_ntp: peerNtp,
  11460. comment
  11461. })
  11462. });
  11463. }
  11464. const data = await res.json();
  11465. if (!res.ok) {
  11466. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11467. return;
  11468. }
  11469. closeDHCPClientModal();
  11470. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11471. await loadDHCPClients();
  11472. fetchData(); // refresh interfaces list with new lease/status
  11473. } catch (err) {
  11474. showToast('Error', err.message, 'error');
  11475. }
  11476. }
  11477. async function toggleDHCPClientState(id, enabled) {
  11478. try {
  11479. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11480. method: 'POST',
  11481. headers: { 'Content-Type': 'application/json' },
  11482. body: JSON.stringify({ enabled })
  11483. });
  11484. const data = await res.json();
  11485. if (!res.ok) {
  11486. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11487. return;
  11488. }
  11489. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11490. await loadDHCPClients();
  11491. fetchData();
  11492. } catch (err) {
  11493. showToast('Error', err.message, 'error');
  11494. }
  11495. }
  11496. async function renewDHCPClient(id) {
  11497. try {
  11498. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11499. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11500. method: 'POST'
  11501. });
  11502. const data = await res.json();
  11503. if (!res.ok) {
  11504. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11505. return;
  11506. }
  11507. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11508. setTimeout(() => {
  11509. loadDHCPClients();
  11510. fetchData();
  11511. }, 1500);
  11512. } catch (err) {
  11513. showToast('Error', err.message, 'error');
  11514. }
  11515. }
  11516. async function releaseDHCPClient(id) {
  11517. try {
  11518. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11519. method: 'POST'
  11520. });
  11521. const data = await res.json();
  11522. if (!res.ok) {
  11523. showToast('Error', data.error || 'Failed to release lease', 'error');
  11524. return;
  11525. }
  11526. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11527. await loadDHCPClients();
  11528. fetchData();
  11529. } catch (err) {
  11530. showToast('Error', err.message, 'error');
  11531. }
  11532. }
  11533. async function deleteDHCPClient(id, ifaceName) {
  11534. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11535. return;
  11536. }
  11537. try {
  11538. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11539. method: 'DELETE'
  11540. });
  11541. const data = await res.json();
  11542. if (!res.ok) {
  11543. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11544. return;
  11545. }
  11546. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11547. await loadDHCPClients();
  11548. fetchData();
  11549. } catch (err) {
  11550. showToast('Error', err.message, 'error');
  11551. }
  11552. }
  11553. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11554. async function loadDHCPServer(populate = true) {
  11555. try {
  11556. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11557. fetch(`${API_BASE}/dhcp-server/summary`),
  11558. fetch(`${API_BASE}/dhcp-server/servers`),
  11559. fetch(`${API_BASE}/dhcp-server/networks`),
  11560. fetch(`${API_BASE}/dhcp-server/leases`),
  11561. fetch(`${API_BASE}/dhcp-server/options`)
  11562. ]);
  11563. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11564. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11565. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11566. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11567. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11568. const sum = state.dhcpServerSummary || {};
  11569. const srvs = state.dhcpServers || [];
  11570. const nets = state.dhcpNetworks || [];
  11571. const leases = state.dhcpLeases || [];
  11572. const opts = state.dhcpOptions || [];
  11573. // KPI Cards
  11574. const statActive = document.getElementById('dhcp-server-stat-active');
  11575. if (statActive) {
  11576. const activeCount = srvs.filter(s => s.running).length;
  11577. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11578. }
  11579. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11580. if (statLeases) {
  11581. statLeases.innerText = leases.length;
  11582. }
  11583. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11584. if (statLeasesSub) {
  11585. const dyn = leases.filter(l => l.dynamic).length;
  11586. const st = leases.filter(l => !l.dynamic).length;
  11587. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11588. }
  11589. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11590. if (statNetworks) {
  11591. statNetworks.innerText = nets.length;
  11592. }
  11593. // Subtab Badges
  11594. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11595. if (bSrv) bSrv.innerText = srvs.length;
  11596. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11597. if (bNet) bNet.innerText = nets.length;
  11598. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11599. if (bLease) bLease.innerText = leases.length;
  11600. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11601. if (bOpt) bOpt.innerText = opts.length;
  11602. // Sidebar Badge
  11603. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11604. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11605. renderCurrentDHCPServerTab();
  11606. } catch (err) {
  11607. console.error('Failed to load DHCP Server:', err);
  11608. }
  11609. }
  11610. function switchDHCPServerTab(tab) {
  11611. state.dhcpServerTab = tab;
  11612. const tabs = ['servers', 'networks', 'leases', 'options'];
  11613. tabs.forEach(t => {
  11614. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11615. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11616. if (panel) {
  11617. if (t === tab) panel.classList.remove('hidden');
  11618. else panel.classList.add('hidden');
  11619. }
  11620. if (btn) {
  11621. if (t === tab) {
  11622. 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';
  11623. } else {
  11624. 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';
  11625. }
  11626. }
  11627. });
  11628. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11629. if (addBtn) {
  11630. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11631. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11632. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11633. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11634. }
  11635. renderCurrentDHCPServerTab();
  11636. }
  11637. function handleDHCPServerPrimaryAdd() {
  11638. const tab = state.dhcpServerTab || 'servers';
  11639. if (tab === 'servers') openAddDHCPServerModal();
  11640. else if (tab === 'networks') openAddDHCPNetworkModal();
  11641. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11642. else if (tab === 'options') openAddDHCPOptionModal();
  11643. }
  11644. function renderCurrentDHCPServerTab() {
  11645. const tab = state.dhcpServerTab || 'servers';
  11646. if (tab === 'servers') renderDHCPServers();
  11647. else if (tab === 'networks') renderDHCPNetworks();
  11648. else if (tab === 'leases') renderDHCPLeases();
  11649. else if (tab === 'options') renderDHCPOptions();
  11650. }
  11651. function renderDHCPServers() {
  11652. const tbody = document.getElementById('dhcp-server-tbody');
  11653. const empty = document.getElementById('dhcp-server-empty');
  11654. if (!tbody) return;
  11655. tbody.innerHTML = '';
  11656. const servers = state.dhcpServers || [];
  11657. if (servers.length === 0) {
  11658. empty?.classList.remove('hidden');
  11659. return;
  11660. }
  11661. empty?.classList.add('hidden');
  11662. servers.forEach(s => {
  11663. const tr = document.createElement('tr');
  11664. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11665. tr.innerHTML = `
  11666. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11667. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11668. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11669. <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>
  11670. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11671. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11672. <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>
  11673. <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>
  11674. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11675. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11676. <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>
  11677. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11678. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11679. </td>
  11680. `;
  11681. tbody.appendChild(tr);
  11682. });
  11683. }
  11684. function renderDHCPNetworks() {
  11685. const tbody = document.getElementById('dhcp-networks-tbody');
  11686. const empty = document.getElementById('dhcp-networks-empty');
  11687. if (!tbody) return;
  11688. tbody.innerHTML = '';
  11689. const networks = state.dhcpNetworks || [];
  11690. if (networks.length === 0) {
  11691. empty?.classList.remove('hidden');
  11692. return;
  11693. }
  11694. empty?.classList.add('hidden');
  11695. networks.forEach(n => {
  11696. const tr = document.createElement('tr');
  11697. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11698. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11699. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11700. tr.innerHTML = `
  11701. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11702. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11703. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11704. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11705. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11706. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11707. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11708. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11709. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11710. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11711. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11712. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11713. </td>
  11714. `;
  11715. tbody.appendChild(tr);
  11716. });
  11717. }
  11718. function renderDHCPLeases() {
  11719. const tbody = document.getElementById('dhcp-leases-tbody');
  11720. const empty = document.getElementById('dhcp-leases-empty');
  11721. if (!tbody) return;
  11722. tbody.innerHTML = '';
  11723. const leases = state.dhcpLeases || [];
  11724. if (leases.length === 0) {
  11725. empty?.classList.remove('hidden');
  11726. return;
  11727. }
  11728. empty?.classList.add('hidden');
  11729. leases.forEach(l => {
  11730. const tr = document.createElement('tr');
  11731. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11732. 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>';
  11733. const statusBadge = l.status === 'bound'
  11734. ? '<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>'
  11735. : l.status === 'static'
  11736. ? '<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>'
  11737. : '<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>';
  11738. const makeStaticBtn = l.dynamic
  11739. ? `<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>`
  11740. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11741. tr.innerHTML = `
  11742. <td class="py-2.5 px-3 text-center">${flag}</td>
  11743. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11744. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11745. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11746. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11747. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11748. <td class="py-2.5 px-3">${statusBadge}</td>
  11749. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11750. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11751. ${makeStaticBtn}
  11752. </td>
  11753. `;
  11754. tbody.appendChild(tr);
  11755. });
  11756. }
  11757. function renderDHCPOptions() {
  11758. const tbody = document.getElementById('dhcp-options-tbody');
  11759. const empty = document.getElementById('dhcp-options-empty');
  11760. if (!tbody) return;
  11761. tbody.innerHTML = '';
  11762. const options = state.dhcpOptions || [];
  11763. if (options.length === 0) {
  11764. empty?.classList.remove('hidden');
  11765. return;
  11766. }
  11767. empty?.classList.add('hidden');
  11768. options.forEach(o => {
  11769. const tr = document.createElement('tr');
  11770. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11771. tr.innerHTML = `
  11772. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11773. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11774. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11775. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11776. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11777. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11778. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11779. </td>
  11780. `;
  11781. tbody.appendChild(tr);
  11782. });
  11783. }
  11784. // ==================== MODALS & ACTIONS: SERVER ====================
  11785. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11786. const sel = document.getElementById(elemId);
  11787. if (!sel) return;
  11788. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11789. const networks = state.dhcpNetworks || [];
  11790. networks.forEach(n => {
  11791. const opt = document.createElement('option');
  11792. opt.value = n.address;
  11793. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11794. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11795. opt.selected = true;
  11796. }
  11797. sel.appendChild(opt);
  11798. });
  11799. }
  11800. function onDHCPServerNetworkChange() {
  11801. const netSel = document.getElementById('dhcp-server-modal-network');
  11802. if (!netSel) return;
  11803. const netVal = netSel.value;
  11804. if (!netVal) return;
  11805. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11806. if (!poolInput) return;
  11807. // Auto-calculate suggested address pool based on subnet CIDR
  11808. const parts = netVal.split('/');
  11809. const ip = parts[0];
  11810. const cidr = parseInt(parts[1] || '24', 10);
  11811. if (cidr === 24) {
  11812. const octets = ip.split('.');
  11813. if (octets.length === 4) {
  11814. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11815. poolInput.value = `${base}.10-${base}.254`;
  11816. }
  11817. }
  11818. }
  11819. function openAddDHCPServerModal() {
  11820. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11821. document.getElementById('dhcp-server-modal-id').value = '';
  11822. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11823. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11824. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11825. document.getElementById('dhcp-server-modal-comment').value = '';
  11826. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11827. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11828. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11829. const networks = state.dhcpNetworks || [];
  11830. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11831. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11832. if (defaultNet) {
  11833. onDHCPServerNetworkChange();
  11834. }
  11835. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11836. }
  11837. function openEditDHCPServerModal(id) {
  11838. const s = (state.dhcpServers || []).find(item => item.id === id);
  11839. if (!s) return;
  11840. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11841. document.getElementById('dhcp-server-modal-id').value = s.id;
  11842. document.getElementById('dhcp-server-modal-name').value = s.name;
  11843. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11844. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11845. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11846. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11847. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11848. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11849. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11850. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11851. }
  11852. function closeDHCPServerModal() {
  11853. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11854. }
  11855. async function submitSaveDHCPServer(e) {
  11856. e.preventDefault();
  11857. const id = document.getElementById('dhcp-server-modal-id').value;
  11858. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11859. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11860. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11861. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11862. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11863. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11864. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11865. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11866. try {
  11867. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11868. method: 'POST',
  11869. headers: { 'Content-Type': 'application/json' },
  11870. body: JSON.stringify({
  11871. id,
  11872. name,
  11873. interface: iface,
  11874. network,
  11875. address_pool: pool,
  11876. lease_time: leaseTime,
  11877. authoritative,
  11878. disabled,
  11879. comment
  11880. })
  11881. });
  11882. if (res.ok) {
  11883. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11884. closeDHCPServerModal();
  11885. loadDHCPServer(false);
  11886. fetchData(false);
  11887. } else {
  11888. const err = await res.text();
  11889. showToast('Error', err, 'error');
  11890. }
  11891. } catch (err) {
  11892. showToast('Error', err.message, 'error');
  11893. }
  11894. }
  11895. async function toggleDHCPServerState(id, disabled) {
  11896. try {
  11897. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11898. method: 'POST',
  11899. headers: { 'Content-Type': 'application/json' },
  11900. body: JSON.stringify({ disabled })
  11901. });
  11902. if (res.ok) {
  11903. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11904. loadDHCPServer(false);
  11905. fetchData(false);
  11906. }
  11907. } catch (err) {
  11908. showToast('Error', err.message, 'error');
  11909. }
  11910. }
  11911. async function deleteDHCPServer(id, name) {
  11912. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11913. try {
  11914. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11915. if (res.ok) {
  11916. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11917. loadDHCPServer(false);
  11918. fetchData(false);
  11919. }
  11920. } catch (err) {
  11921. showToast('Error', err.message, 'error');
  11922. }
  11923. }
  11924. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11925. function openAddDHCPNetworkModal() {
  11926. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11927. document.getElementById('dhcp-network-modal-id').value = '';
  11928. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11929. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11930. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11931. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11932. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11933. document.getElementById('dhcp-network-modal-tftp').value = '';
  11934. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11935. document.getElementById('dhcp-network-modal-wins').value = '';
  11936. document.getElementById('dhcp-network-modal-netmask').value = '';
  11937. document.getElementById('dhcp-network-modal-comment').value = '';
  11938. renderDHCPNetworkOptionsCheckboxes([]);
  11939. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11940. }
  11941. function openEditDHCPNetworkModal(id) {
  11942. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11943. if (!n) return;
  11944. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11945. document.getElementById('dhcp-network-modal-id').value = n.id;
  11946. document.getElementById('dhcp-network-modal-address').value = n.address;
  11947. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11948. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11949. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11950. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11951. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11952. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11953. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11954. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11955. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11956. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11957. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11958. }
  11959. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  11960. const container = document.getElementById('dhcp-network-modal-options-list');
  11961. if (!container) return;
  11962. container.innerHTML = '';
  11963. const opts = state.dhcpOptions || [];
  11964. if (opts.length === 0) {
  11965. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  11966. return;
  11967. }
  11968. opts.forEach(o => {
  11969. const isChecked = selectedIds.includes(o.id);
  11970. const label = document.createElement('label');
  11971. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  11972. label.innerHTML = `
  11973. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  11974. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  11975. `;
  11976. container.appendChild(label);
  11977. });
  11978. }
  11979. function closeDHCPNetworkModal() {
  11980. document.getElementById('dhcp-network-modal').classList.add('hidden');
  11981. }
  11982. async function submitSaveDHCPNetwork(e) {
  11983. e.preventDefault();
  11984. const id = document.getElementById('dhcp-network-modal-id').value;
  11985. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  11986. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  11987. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  11988. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  11989. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  11990. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  11991. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  11992. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  11993. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  11994. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  11995. const selectedOpts = [];
  11996. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  11997. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11998. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11999. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12000. try {
  12001. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12002. method: 'POST',
  12003. headers: { 'Content-Type': 'application/json' },
  12004. body: JSON.stringify({
  12005. id,
  12006. address,
  12007. gateway,
  12008. netmask,
  12009. dns_servers: dnsServers,
  12010. domain,
  12011. ntp_servers: ntpServers,
  12012. next_server: tftp,
  12013. boot_file_name: bootfile,
  12014. wins_servers: winsServers,
  12015. dhcp_options: selectedOpts,
  12016. comment
  12017. })
  12018. });
  12019. if (res.ok) {
  12020. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12021. closeDHCPNetworkModal();
  12022. loadDHCPServer(false);
  12023. fetchData(false);
  12024. } else {
  12025. const err = await res.text();
  12026. showToast('Error', err, 'error');
  12027. }
  12028. } catch (err) {
  12029. showToast('Error', err.message, 'error');
  12030. }
  12031. }
  12032. async function deleteDHCPNetwork(id, addr) {
  12033. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12034. try {
  12035. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12036. if (res.ok) {
  12037. showToast('Deleted', `Network ${addr} removed`, 'success');
  12038. loadDHCPServer(false);
  12039. fetchData(false);
  12040. }
  12041. } catch (err) {
  12042. showToast('Error', err.message, 'error');
  12043. }
  12044. }
  12045. // ==================== MODALS & ACTIONS: LEASES ====================
  12046. function openAddDHCPStaticLeaseModal() {
  12047. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12048. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12049. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12050. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12051. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12052. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12053. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12054. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12055. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12056. }
  12057. function closeDHCPStaticLeaseModal() {
  12058. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12059. }
  12060. async function submitSaveDHCPStaticLease(e) {
  12061. e.preventDefault();
  12062. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12063. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12064. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12065. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12066. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12067. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12068. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12069. try {
  12070. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12071. method: 'POST',
  12072. headers: { 'Content-Type': 'application/json' },
  12073. body: JSON.stringify({
  12074. id,
  12075. mac_address: mac,
  12076. address: ip,
  12077. hostname,
  12078. server,
  12079. comment,
  12080. disabled
  12081. })
  12082. });
  12083. if (res.ok) {
  12084. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12085. closeDHCPStaticLeaseModal();
  12086. loadDHCPServer(false);
  12087. fetchData(false);
  12088. } else {
  12089. const err = await res.text();
  12090. showToast('Error', err, 'error');
  12091. }
  12092. } catch (err) {
  12093. showToast('Error', err.message, 'error');
  12094. }
  12095. }
  12096. async function deleteDHCPStaticLease(id) {
  12097. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12098. try {
  12099. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12100. if (res.ok) {
  12101. showToast('Deleted', 'Static lease removed', 'success');
  12102. loadDHCPServer(false);
  12103. fetchData(false);
  12104. }
  12105. } catch (err) {
  12106. showToast('Error', err.message, 'error');
  12107. }
  12108. }
  12109. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12110. try {
  12111. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12112. method: 'POST',
  12113. headers: { 'Content-Type': 'application/json' },
  12114. body: JSON.stringify({
  12115. mac_address: mac,
  12116. address: ip,
  12117. hostname,
  12118. comment: comment || 'Converted to static'
  12119. })
  12120. });
  12121. if (res.ok) {
  12122. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12123. loadDHCPServer(false);
  12124. fetchData(false);
  12125. } else {
  12126. const err = await res.text();
  12127. showToast('Error', err, 'error');
  12128. }
  12129. } catch (err) {
  12130. showToast('Error', err.message, 'error');
  12131. }
  12132. }
  12133. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12134. function openAddDHCPOptionModal() {
  12135. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12136. document.getElementById('dhcp-option-modal-id').value = '';
  12137. document.getElementById('dhcp-option-modal-name').value = '';
  12138. document.getElementById('dhcp-option-modal-code').value = '';
  12139. document.getElementById('dhcp-option-modal-value').value = '';
  12140. document.getElementById('dhcp-option-modal-comment').value = '';
  12141. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12142. }
  12143. function openEditDHCPOptionModal(id) {
  12144. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12145. if (!o) return;
  12146. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12147. document.getElementById('dhcp-option-modal-id').value = o.id;
  12148. document.getElementById('dhcp-option-modal-name').value = o.name;
  12149. document.getElementById('dhcp-option-modal-code').value = o.code;
  12150. document.getElementById('dhcp-option-modal-value').value = o.value;
  12151. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12152. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12153. }
  12154. function closeDHCPOptionModal() {
  12155. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12156. }
  12157. async function submitSaveDHCPOption(e) {
  12158. e.preventDefault();
  12159. const id = document.getElementById('dhcp-option-modal-id').value;
  12160. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12161. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12162. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12163. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12164. try {
  12165. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12166. method: 'POST',
  12167. headers: { 'Content-Type': 'application/json' },
  12168. body: JSON.stringify({ id, name, code, value, comment })
  12169. });
  12170. if (res.ok) {
  12171. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12172. closeDHCPOptionModal();
  12173. loadDHCPServer(false);
  12174. fetchData(false);
  12175. } else {
  12176. const err = await res.text();
  12177. showToast('Error', err, 'error');
  12178. }
  12179. } catch (err) {
  12180. showToast('Error', err.message, 'error');
  12181. }
  12182. }
  12183. async function deleteDHCPOption(id, name) {
  12184. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12185. try {
  12186. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12187. if (res.ok) {
  12188. showToast('Deleted', `Option ${name} removed`, 'success');
  12189. loadDHCPServer(false);
  12190. fetchData(false);
  12191. }
  12192. } catch (err) {
  12193. showToast('Error', err.message, 'error');
  12194. }
  12195. }
  12196. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12197. function openDHCPServerSetupModal() {
  12198. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12199. onDHCPWizardIfaceChange();
  12200. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12201. }
  12202. function closeDHCPServerSetupModal() {
  12203. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12204. }
  12205. function onDHCPWizardIfaceChange() {
  12206. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12207. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12208. let ip = '192.168.88.1';
  12209. let prefix = '24';
  12210. if (iface && iface.ip_address) {
  12211. const parts = iface.ip_address.split('/');
  12212. ip = parts[0];
  12213. if (parts.length > 1) prefix = parts[1];
  12214. }
  12215. // Calculate subnet base (e.g. 192.168.88.0/24)
  12216. const ipParts = ip.split('.');
  12217. if (ipParts.length === 4) {
  12218. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12219. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12220. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12221. document.getElementById('dhcp-wizard-gateway').value = ip;
  12222. document.getElementById('dhcp-wizard-pool').value = pool;
  12223. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12224. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12225. }
  12226. }
  12227. async function submitDHCPServerSetupWizard(e) {
  12228. e.preventDefault();
  12229. const iface = document.getElementById('dhcp-wizard-iface').value;
  12230. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12231. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12232. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12233. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12234. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12235. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12236. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12237. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12238. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12239. try {
  12240. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12241. method: 'POST',
  12242. headers: { 'Content-Type': 'application/json' },
  12243. body: JSON.stringify({
  12244. interface: iface,
  12245. address_space: space,
  12246. gateway: gw,
  12247. address_pool: pool,
  12248. dns_servers: dnsServers,
  12249. lease_time: leaseTime,
  12250. ntp_servers: ntpServers,
  12251. next_server: tftp
  12252. })
  12253. });
  12254. if (res.ok) {
  12255. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12256. closeDHCPServerSetupModal();
  12257. loadDHCPServer(false);
  12258. fetchData(false);
  12259. } else {
  12260. const err = await res.text();
  12261. showToast('Error', err, 'error');
  12262. }
  12263. } catch (err) {
  12264. showToast('Error', err.message, 'error');
  12265. }
  12266. }
  12267. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12268. const sel = document.getElementById(elemId);
  12269. if (!sel) return;
  12270. sel.innerHTML = '<option value="">Select interface...</option>';
  12271. const ifaces = state.interfaces || [];
  12272. ifaces.forEach(i => {
  12273. if (i.name === 'lo') return;
  12274. const opt = document.createElement('option');
  12275. opt.value = i.name;
  12276. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12277. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12278. if (i.name === selectedVal) opt.selected = true;
  12279. sel.appendChild(opt);
  12280. });
  12281. }
  12282. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12283. function initTableSorting() {
  12284. document.querySelectorAll('table').forEach(setupSortableTable);
  12285. }
  12286. function setupSortableTable(table) {
  12287. const thead = table.querySelector('thead');
  12288. const tbody = table.querySelector('tbody');
  12289. if (!thead || !tbody) return;
  12290. const headerRows = thead.querySelectorAll('tr');
  12291. if (headerRows.length === 0) return;
  12292. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12293. ths.forEach((th, colIdx) => {
  12294. if (th._sortBound) return;
  12295. th._sortBound = true;
  12296. const rawText = th.innerText.trim().toLowerCase();
  12297. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12298. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12299. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12300. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12301. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12302. return;
  12303. }
  12304. th.classList.add('table-sortable', 'group');
  12305. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12306. let icon = th.querySelector('.table-sort-icon');
  12307. if (!icon) {
  12308. icon = document.createElement('span');
  12309. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12310. icon.innerHTML = '⇅';
  12311. th.appendChild(icon);
  12312. }
  12313. th.addEventListener('click', (e) => {
  12314. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12315. handleHeaderClick(table, th, colIdx);
  12316. });
  12317. });
  12318. if (!tbody._sortObserved) {
  12319. tbody._sortObserved = true;
  12320. let sortDebounceTimer = null;
  12321. const observer = new MutationObserver((mutations) => {
  12322. if (tbody._isSorting) return;
  12323. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12324. if (!hasChildChanges) return;
  12325. clearTimeout(sortDebounceTimer);
  12326. sortDebounceTimer = setTimeout(() => {
  12327. if (tbody._isSorting) return;
  12328. if (table._activeSort && table._activeSort.dir !== 'none') {
  12329. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12330. } else {
  12331. tagOriginalRowOrder(tbody);
  12332. }
  12333. }, 10);
  12334. });
  12335. observer.observe(tbody, { childList: true });
  12336. }
  12337. tagOriginalRowOrder(tbody);
  12338. }
  12339. function tagOriginalRowOrder(tbody) {
  12340. let idx = 0;
  12341. Array.from(tbody.children).forEach(tr => {
  12342. if (!tr.querySelector('td[colspan]')) {
  12343. if (!tr.hasAttribute('data-orig-idx')) {
  12344. tr.setAttribute('data-orig-idx', idx++);
  12345. }
  12346. }
  12347. });
  12348. }
  12349. function handleHeaderClick(table, th, colIdx) {
  12350. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12351. let newDir = 'asc';
  12352. if (currentSort.colIdx === colIdx) {
  12353. if (currentSort.dir === 'asc') newDir = 'desc';
  12354. else if (currentSort.dir === 'desc') newDir = 'none';
  12355. else newDir = 'asc';
  12356. } else {
  12357. newDir = 'asc';
  12358. }
  12359. table._activeSort = { colIdx, dir: newDir };
  12360. updateHeaderIcons(table, colIdx, newDir);
  12361. applyTableSort(table, colIdx, newDir, true);
  12362. }
  12363. function updateHeaderIcons(table, activeColIdx, dir) {
  12364. const thead = table.querySelector('thead');
  12365. if (!thead) return;
  12366. const ths = thead.querySelectorAll('th');
  12367. ths.forEach((th, idx) => {
  12368. const icon = th.querySelector('.table-sort-icon');
  12369. if (!icon) return;
  12370. if (idx === activeColIdx && dir !== 'none') {
  12371. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12372. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12373. th.classList.add('table-sorted-active');
  12374. } else {
  12375. icon.innerHTML = '⇅';
  12376. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12377. th.classList.remove('table-sorted-active');
  12378. }
  12379. });
  12380. }
  12381. function applyTableSort(table, colIdx, dir, userInitiated) {
  12382. const tbody = table.querySelector('tbody');
  12383. if (!tbody || tbody.children.length <= 1) return;
  12384. tbody._isSorting = true;
  12385. tagOriginalRowOrder(tbody);
  12386. // Group parent rows and any attached drawer/sub-rows
  12387. const groups = [];
  12388. let currentGroup = null;
  12389. Array.from(tbody.children).forEach(tr => {
  12390. if (tr.querySelector('td[colspan]')) {
  12391. if (currentGroup) {
  12392. currentGroup.subRows.push(tr);
  12393. } else {
  12394. groups.push({ mainRow: tr, subRows: [] });
  12395. }
  12396. } else {
  12397. currentGroup = { mainRow: tr, subRows: [] };
  12398. groups.push(currentGroup);
  12399. }
  12400. });
  12401. if (dir === 'none') {
  12402. groups.sort((a, b) => {
  12403. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12404. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12405. return idxA - idxB;
  12406. });
  12407. } else {
  12408. groups.sort((a, b) => {
  12409. const cellA = a.mainRow.children[colIdx];
  12410. const cellB = b.mainRow.children[colIdx];
  12411. const res = compareTableCells(cellA, cellB);
  12412. return dir === 'asc' ? res : -res;
  12413. });
  12414. }
  12415. // Re-append rows in sorted order
  12416. groups.forEach(g => {
  12417. tbody.appendChild(g.mainRow);
  12418. g.subRows.forEach(sub => tbody.appendChild(sub));
  12419. });
  12420. tbody._isSorting = false;
  12421. }
  12422. function getCellRawText(cell) {
  12423. if (!cell) return '';
  12424. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12425. const input = cell.querySelector('input, select');
  12426. if (input) {
  12427. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12428. return input.value;
  12429. }
  12430. return cell.innerText.trim();
  12431. }
  12432. function parseTrafficToNumber(str) {
  12433. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12434. if (!m) return null;
  12435. const num = parseFloat(m[1].replace(/,/g, ''));
  12436. if (isNaN(num)) return null;
  12437. const unit = m[2].toUpperCase();
  12438. let mult = 1;
  12439. if (unit.startsWith('K')) mult = 1024;
  12440. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12441. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12442. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12443. return num * mult;
  12444. }
  12445. function parseIpToNumber(str) {
  12446. const clean = str.replace(/^[!~]/, '').trim();
  12447. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12448. if (!m) return null;
  12449. const o1 = parseInt(m[1], 10);
  12450. const o2 = parseInt(m[2], 10);
  12451. const o3 = parseInt(m[3], 10);
  12452. const o4 = parseInt(m[4], 10);
  12453. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12454. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12455. }
  12456. function parseCompoundPackets(str) {
  12457. const m = str.match(/^([\d,]+)p/);
  12458. if (!m) return null;
  12459. return parseInt(m[1].replace(/,/g, ''), 10);
  12460. }
  12461. function compareTableCells(cellA, cellB) {
  12462. const a = getCellRawText(cellA);
  12463. const b = getCellRawText(cellB);
  12464. if (a === '' && b !== '') return 1;
  12465. if (b === '' && a !== '') return -1;
  12466. if (a === b) return 0;
  12467. // 1. IP Addresses / CIDR
  12468. const ipA = parseIpToNumber(a);
  12469. const ipB = parseIpToNumber(b);
  12470. if (ipA !== null && ipB !== null) return ipA - ipB;
  12471. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12472. const pktA = parseCompoundPackets(a);
  12473. const pktB = parseCompoundPackets(b);
  12474. if (pktA !== null && pktB !== null) return pktA - pktB;
  12475. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12476. const trafA = parseTrafficToNumber(a);
  12477. const trafB = parseTrafficToNumber(b);
  12478. if (trafA !== null && trafB !== null) return trafA - trafB;
  12479. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12480. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12481. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12482. const numA = Number(cleanNumA);
  12483. const numB = Number(cleanNumB);
  12484. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12485. return numA - numB;
  12486. }
  12487. // 5. Natural case-insensitive string compare
  12488. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12489. }
  12490. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12491. async function loadVRRP(showToastNotification = false) {
  12492. try {
  12493. const [instRes, sumRes] = await Promise.all([
  12494. fetch(`${API_BASE}/vrrp/instances`),
  12495. fetch(`${API_BASE}/vrrp/summary`)
  12496. ]);
  12497. if (instRes.ok) {
  12498. state.vrrpInstances = await instRes.json();
  12499. renderVRRP();
  12500. }
  12501. if (sumRes.ok) {
  12502. state.vrrpSummary = await sumRes.json();
  12503. renderVRRPSummary();
  12504. }
  12505. if (showToastNotification) {
  12506. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12507. }
  12508. } catch (err) {
  12509. console.error('Failed to load VRRP:', err);
  12510. }
  12511. }
  12512. function renderVRRPSummary() {
  12513. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12514. const elTotal = document.getElementById('vrrp-stat-total');
  12515. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12516. const elMaster = document.getElementById('vrrp-stat-master');
  12517. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12518. const elBackup = document.getElementById('vrrp-stat-backup');
  12519. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12520. const bCount = document.getElementById('badge-vrrp-count');
  12521. if (bCount) bCount.innerText = s.total_instances || 0;
  12522. const dot = document.getElementById('badge-vrrp-dot');
  12523. if (dot) {
  12524. if (s.master_instances > 0) {
  12525. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12526. } else if (s.backup_instances > 0) {
  12527. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12528. } else {
  12529. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12530. }
  12531. }
  12532. }
  12533. function renderVRRP() {
  12534. const tbody = document.getElementById('vrrp-table-tbody');
  12535. const empty = document.getElementById('vrrp-table-empty');
  12536. if (!tbody) return;
  12537. tbody.innerHTML = '';
  12538. const instances = state.vrrpInstances || [];
  12539. if (instances.length === 0) {
  12540. empty?.classList.remove('hidden');
  12541. return;
  12542. }
  12543. empty?.classList.add('hidden');
  12544. instances.forEach(inst => {
  12545. const tr = document.createElement('tr');
  12546. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12547. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12548. 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>`;
  12549. if (inst.disabled) {
  12550. 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>`;
  12551. } else if (inst.state === 'MASTER') {
  12552. 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>`;
  12553. } else if (inst.state === 'BACKUP') {
  12554. 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>`;
  12555. } else if (inst.state === 'FAULT') {
  12556. 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>`;
  12557. }
  12558. // Render State Badge
  12559. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12560. if (!inst.disabled) {
  12561. if (inst.state === 'MASTER') {
  12562. 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>`;
  12563. } else if (inst.state === 'BACKUP') {
  12564. 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>`;
  12565. } else if (inst.state === 'FAULT') {
  12566. 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>`;
  12567. }
  12568. }
  12569. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12570. tr.innerHTML = `
  12571. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12572. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12573. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12574. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12575. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12576. <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>
  12577. <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>
  12578. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12579. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12580. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12581. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12582. <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>
  12583. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12584. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12585. </td>
  12586. `;
  12587. tbody.appendChild(tr);
  12588. });
  12589. }
  12590. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12591. const sel = document.getElementById(elemId);
  12592. if (!sel) return;
  12593. sel.innerHTML = '<option value="">Select interface...</option>';
  12594. const ifaces = state.interfaces || [];
  12595. ifaces.forEach(i => {
  12596. const opt = document.createElement('option');
  12597. opt.value = i.name;
  12598. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12599. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12600. sel.appendChild(opt);
  12601. });
  12602. }
  12603. function openAddVRRPModal() {
  12604. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12605. document.getElementById('modal-vrrp-id').value = '';
  12606. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12607. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12608. document.getElementById('modal-vrrp-priority').value = 100;
  12609. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12610. document.getElementById('modal-vrrp-version').value = '3';
  12611. document.getElementById('modal-vrrp-interval').value = 1;
  12612. document.getElementById('modal-vrrp-authtype').value = 'none';
  12613. document.getElementById('modal-vrrp-authpass').value = '';
  12614. document.getElementById('modal-vrrp-comment').value = '';
  12615. document.getElementById('modal-vrrp-preempt').checked = true;
  12616. document.getElementById('modal-vrrp-disabled').checked = false;
  12617. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12618. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12619. }
  12620. function openEditVRRPModal(id) {
  12621. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12622. if (!inst) return;
  12623. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12624. document.getElementById('modal-vrrp-id').value = inst.id;
  12625. document.getElementById('modal-vrrp-name').value = inst.name;
  12626. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12627. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12628. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12629. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12630. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12631. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12632. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12633. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12634. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12635. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12636. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12637. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12638. }
  12639. function closeVRRPModal() {
  12640. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12641. }
  12642. async function submitSaveVRRP(e) {
  12643. e.preventDefault();
  12644. const id = document.getElementById('modal-vrrp-id').value;
  12645. const name = document.getElementById('modal-vrrp-name').value.trim();
  12646. const iface = document.getElementById('modal-vrrp-iface').value;
  12647. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12648. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12649. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12650. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12651. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12652. const authType = document.getElementById('modal-vrrp-authtype').value;
  12653. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12654. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12655. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12656. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12657. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12658. try {
  12659. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12660. method: 'POST',
  12661. headers: { 'Content-Type': 'application/json' },
  12662. body: JSON.stringify({
  12663. id,
  12664. name,
  12665. interface: iface,
  12666. vrid,
  12667. priority,
  12668. virtual_ips: vips,
  12669. version,
  12670. interval,
  12671. auth_type: authType,
  12672. auth_password: authPass,
  12673. comment,
  12674. preempt,
  12675. disabled
  12676. })
  12677. });
  12678. if (res.ok) {
  12679. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12680. closeVRRPModal();
  12681. loadVRRP(false);
  12682. fetchData(false);
  12683. } else {
  12684. const err = await res.text();
  12685. showToast('Error', err, 'error');
  12686. }
  12687. } catch (err) {
  12688. showToast('Error', err.message, 'error');
  12689. }
  12690. }
  12691. async function deleteVRRP(id, name) {
  12692. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12693. try {
  12694. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12695. if (res.ok) {
  12696. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12697. loadVRRP(false);
  12698. fetchData(false);
  12699. } else {
  12700. const err = await res.text();
  12701. showToast('Error', err, 'error');
  12702. }
  12703. } catch (err) {
  12704. showToast('Error', err.message, 'error');
  12705. }
  12706. }
  12707. async function toggleVRRPState(id, disabled) {
  12708. try {
  12709. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12710. method: 'POST',
  12711. headers: { 'Content-Type': 'application/json' },
  12712. body: JSON.stringify({ disabled })
  12713. });
  12714. if (res.ok) {
  12715. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12716. loadVRRP(false);
  12717. fetchData(false);
  12718. } else {
  12719. const err = await res.text();
  12720. showToast('Error', err, 'error');
  12721. }
  12722. } catch (err) {
  12723. showToast('Error', err.message, 'error');
  12724. }
  12725. }
  12726. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12727. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12728. const docTableObserver = new MutationObserver((mutations) => {
  12729. let needsInit = false;
  12730. for (const m of mutations) {
  12731. for (const node of m.addedNodes) {
  12732. if (node.nodeType === 1) {
  12733. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12734. needsInit = true;
  12735. break;
  12736. }
  12737. }
  12738. }
  12739. if (needsInit) break;
  12740. }
  12741. if (needsInit) {
  12742. initTableSorting();
  12743. }
  12744. });
  12745. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12746. }
  12747. // =========================================================================
  12748. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  12749. // =========================================================================
  12750. const bwtestState = {
  12751. running: false,
  12752. pollTimer: null,
  12753. eventSource: null,
  12754. chartPoints: [],
  12755. maxChartPoints: 60,
  12756. serverConfig: null,
  12757. peakTx: 0,
  12758. peakRx: 0,
  12759. targetDuration: 10,
  12760. lastSampleIndex: 0
  12761. };
  12762. async function loadBwTestView() {
  12763. fetchBwTestServerStatus();
  12764. loadBwTestHistory();
  12765. resizeBwTestCanvas();
  12766. checkActiveBwTest();
  12767. }
  12768. async function fetchBwTestServerStatus() {
  12769. try {
  12770. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  12771. if (!res.ok) return;
  12772. const s = await res.json();
  12773. bwtestState.serverConfig = s;
  12774. // Update indicator and badges
  12775. const indicator = document.getElementById('bwtest-server-indicator');
  12776. const badge = document.getElementById('bwtest-server-badge');
  12777. const sideBadge = document.getElementById('badge-bwtest-server');
  12778. if (s.enabled && s.running) {
  12779. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12780. if (badge) {
  12781. badge.innerText = `Port ${s.port} (Active)`;
  12782. badge.className = 'text-emerald-400 font-bold';
  12783. }
  12784. if (sideBadge) {
  12785. sideBadge.innerText = s.port;
  12786. 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';
  12787. }
  12788. } else {
  12789. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  12790. if (badge) {
  12791. badge.innerText = `Disabled`;
  12792. badge.className = 'text-slate-500 font-bold';
  12793. }
  12794. if (sideBadge) {
  12795. sideBadge.innerText = 'Off';
  12796. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  12797. }
  12798. }
  12799. // Modal fields
  12800. const toggle = document.getElementById('bwtest-server-enable-toggle');
  12801. if (toggle) toggle.checked = !!s.enabled;
  12802. const portInp = document.getElementById('bwtest-server-port-input');
  12803. if (portInp) portInp.value = s.port || 2000;
  12804. const actSess = document.getElementById('bwtest-modal-active-sessions');
  12805. if (actSess) actSess.innerText = s.active_sessions || 0;
  12806. const totServ = document.getElementById('bwtest-modal-total-served');
  12807. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  12808. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  12809. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  12810. } catch (err) {
  12811. console.error('Failed to fetch BwTest server status:', err);
  12812. }
  12813. }
  12814. function openBwTestServerModal() {
  12815. fetchBwTestServerStatus();
  12816. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  12817. }
  12818. function closeBwTestServerModal() {
  12819. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  12820. }
  12821. async function submitBwTestServerSettings(e) {
  12822. e.preventDefault();
  12823. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  12824. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  12825. try {
  12826. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  12827. method: 'POST',
  12828. headers: { 'Content-Type': 'application/json' },
  12829. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  12830. });
  12831. if (!res.ok) {
  12832. const err = await res.json();
  12833. throw new Error(err.error || 'Failed to update server configuration');
  12834. }
  12835. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  12836. closeBwTestServerModal();
  12837. fetchBwTestServerStatus();
  12838. } catch (err) {
  12839. showToast('Server Configuration Error', err.message, 'error');
  12840. }
  12841. }
  12842. function setBwTestTarget(target) {
  12843. const inp = document.getElementById('bwtest-input-target');
  12844. if (inp) inp.value = target;
  12845. }
  12846. function setBwTestProtocol(proto) {
  12847. const hiddenInp = document.getElementById('bwtest-input-protocol');
  12848. if (hiddenInp) hiddenInp.value = proto;
  12849. const btnUdp = document.getElementById('bwtest-proto-udp');
  12850. const btnTcp = document.getElementById('bwtest-proto-tcp');
  12851. const badge = document.getElementById('bwtest-proto-badge');
  12852. const pktField = document.getElementById('bwtest-field-pktsize');
  12853. 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';
  12854. 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';
  12855. 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';
  12856. if (proto === 'udp') {
  12857. if (btnUdp) {
  12858. btnUdp.className = activeUdpCls;
  12859. const dot = btnUdp.querySelector('span');
  12860. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  12861. }
  12862. if (btnTcp) {
  12863. btnTcp.className = inactiveCls;
  12864. const dot = btnTcp.querySelector('span');
  12865. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12866. }
  12867. if (badge) {
  12868. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  12869. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  12870. }
  12871. if (pktField) pktField.classList.remove('opacity-40');
  12872. } else {
  12873. if (btnUdp) {
  12874. btnUdp.className = inactiveCls;
  12875. const dot = btnUdp.querySelector('span');
  12876. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12877. }
  12878. if (btnTcp) {
  12879. btnTcp.className = activeTcpCls;
  12880. const dot = btnTcp.querySelector('span');
  12881. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  12882. }
  12883. if (badge) {
  12884. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  12885. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  12886. }
  12887. if (pktField) pktField.classList.add('opacity-40');
  12888. }
  12889. }
  12890. function setBwTestDirection(dir) {
  12891. const hiddenInp = document.getElementById('bwtest-input-direction');
  12892. if (hiddenInp) hiddenInp.value = dir;
  12893. const btnBoth = document.getElementById('bwtest-dir-both');
  12894. const btnTx = document.getElementById('bwtest-dir-tx');
  12895. const btnRx = document.getElementById('bwtest-dir-rx');
  12896. 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';
  12897. 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';
  12898. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  12899. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  12900. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  12901. }
  12902. function setBwTestLimit(bps) {
  12903. const sel = document.getElementById('bwtest-input-limit');
  12904. if (sel) sel.value = String(bps);
  12905. }
  12906. async function checkActiveBwTest() {
  12907. try {
  12908. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  12909. if (!res.ok) return;
  12910. const st = await res.json();
  12911. if (st.running) {
  12912. setBwTestRunningUI(true);
  12913. if (st.current_sample) handleBwTestSample(st.current_sample);
  12914. startBwTestTelemetry();
  12915. }
  12916. } catch (err) {
  12917. console.error('Failed to check active BwTest:', err);
  12918. }
  12919. }
  12920. async function startBwTest(e) {
  12921. if (e && e.preventDefault) e.preventDefault();
  12922. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  12923. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  12924. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  12925. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  12926. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  12927. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  12928. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  12929. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  12930. bwtestState.targetDuration = duration;
  12931. bwtestState.chartPoints = [];
  12932. bwtestState.peakTx = 0;
  12933. bwtestState.peakRx = 0;
  12934. bwtestState.lastSampleIndex = 0;
  12935. // Clear UI elements
  12936. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  12937. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  12938. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  12939. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  12940. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  12941. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  12942. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  12943. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  12944. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  12945. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  12946. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  12947. const tbody = document.getElementById('bwtest-samples-tbody');
  12948. if (tbody) tbody.innerHTML = '';
  12949. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  12950. setBwTestRunningUI(true);
  12951. try {
  12952. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  12953. method: 'POST',
  12954. headers: { 'Content-Type': 'application/json' },
  12955. body: JSON.stringify({
  12956. target,
  12957. port,
  12958. direction,
  12959. protocol,
  12960. bandwidth_limit,
  12961. packet_size,
  12962. streams,
  12963. duration
  12964. })
  12965. });
  12966. if (!res.ok) {
  12967. const err = await res.json();
  12968. throw new Error(err.error || 'Failed to start bandwidth test');
  12969. }
  12970. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  12971. startBwTestTelemetry();
  12972. } catch (err) {
  12973. setBwTestRunningUI(false);
  12974. showToast('Start Failed', err.message, 'error');
  12975. }
  12976. }
  12977. function setBwTestRunningUI(running) {
  12978. bwtestState.running = running;
  12979. const startBtn = document.getElementById('bwtest-btn-start');
  12980. const stopBtn = document.getElementById('bwtest-btn-stop');
  12981. const badge = document.getElementById('bwtest-run-status-badge');
  12982. const ph = document.getElementById('bwtest-chart-placeholder');
  12983. if (running) {
  12984. if (startBtn) {
  12985. startBtn.disabled = true;
  12986. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  12987. }
  12988. if (stopBtn) {
  12989. stopBtn.disabled = false;
  12990. stopBtn.classList.remove('opacity-40');
  12991. }
  12992. if (badge) {
  12993. badge.innerText = 'TESTING...';
  12994. 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';
  12995. }
  12996. if (ph) ph.style.display = 'none';
  12997. } else {
  12998. if (startBtn) {
  12999. startBtn.disabled = false;
  13000. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13001. }
  13002. if (stopBtn) {
  13003. stopBtn.disabled = true;
  13004. stopBtn.classList.add('opacity-40');
  13005. }
  13006. if (badge) {
  13007. badge.innerText = 'IDLE';
  13008. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13009. }
  13010. }
  13011. }
  13012. async function stopBwTest() {
  13013. try {
  13014. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13015. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13016. } catch (err) {
  13017. console.error('Failed to stop test:', err);
  13018. }
  13019. }
  13020. function startBwTestTelemetry() {
  13021. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13022. bwtestState.pollTimer = setInterval(async () => {
  13023. try {
  13024. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13025. if (!res.ok) return;
  13026. const st = await res.json();
  13027. if (st.recent_samples && st.recent_samples.length > 0) {
  13028. // Process new samples
  13029. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13030. newSamples.forEach(s => handleBwTestSample(s));
  13031. bwtestState.lastSampleIndex = st.recent_samples.length;
  13032. }
  13033. if (!st.running) {
  13034. clearInterval(bwtestState.pollTimer);
  13035. bwtestState.pollTimer = null;
  13036. setBwTestRunningUI(false);
  13037. handleBwTestFinish(st.summary, st.error);
  13038. }
  13039. } catch (err) {
  13040. console.error('BwTest polling error:', err);
  13041. }
  13042. }, 400);
  13043. }
  13044. function handleBwTestSample(s) {
  13045. if (!s) return;
  13046. const txMbps = s.tx_mbps || 0;
  13047. const rxMbps = s.rx_mbps || 0;
  13048. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13049. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13050. // KPI updates
  13051. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13052. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13053. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13054. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13055. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13056. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13057. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13058. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13059. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13060. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13061. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13062. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13063. const elLoss = document.getElementById('bwtest-stat-loss');
  13064. if (elLoss) {
  13065. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13066. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13067. }
  13068. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13069. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13070. const elJitter = document.getElementById('bwtest-stat-jitter');
  13071. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13072. const elTime = document.getElementById('bwtest-stat-time');
  13073. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13074. const elData = document.getElementById('bwtest-stat-data');
  13075. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13076. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13077. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13078. // Append point to chart buffer
  13079. bwtestState.chartPoints.push({
  13080. elapsed: s.elapsed_sec || 0,
  13081. tx: txMbps,
  13082. rx: rxMbps
  13083. });
  13084. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13085. bwtestState.chartPoints.shift();
  13086. }
  13087. drawBwTestChart();
  13088. // Add row to breakdown table
  13089. const tbody = document.getElementById('bwtest-samples-tbody');
  13090. if (tbody) {
  13091. const tr = document.createElement('tr');
  13092. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13093. tr.innerHTML = `
  13094. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13095. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13096. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13097. <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>
  13098. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13099. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13100. `;
  13101. tbody.insertBefore(tr, tbody.firstChild);
  13102. const countEl = document.getElementById('bwtest-sample-count');
  13103. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13104. }
  13105. }
  13106. function handleBwTestFinish(summary, error) {
  13107. const badge = document.getElementById('bwtest-run-status-badge');
  13108. if (error) {
  13109. showToast('Benchmark Error', error, 'error');
  13110. if (badge) {
  13111. badge.innerText = 'ERROR';
  13112. 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';
  13113. }
  13114. } else if (summary) {
  13115. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13116. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13117. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13118. if (badge) {
  13119. badge.innerText = 'COMPLETED';
  13120. 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';
  13121. }
  13122. }
  13123. loadBwTestHistory();
  13124. fetchBwTestServerStatus();
  13125. }
  13126. function resizeBwTestCanvas() {
  13127. const canvas = document.getElementById('bwtest-chart');
  13128. if (!canvas || !canvas.parentElement) return;
  13129. const rect = canvas.parentElement.getBoundingClientRect();
  13130. const dpr = window.devicePixelRatio || 1;
  13131. canvas.width = rect.width * dpr;
  13132. canvas.height = rect.height * dpr;
  13133. const ctx = canvas.getContext('2d');
  13134. ctx.scale(dpr, dpr);
  13135. drawBwTestChart();
  13136. }
  13137. window.addEventListener('resize', () => {
  13138. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13139. });
  13140. function drawBwTestChart() {
  13141. const canvas = document.getElementById('bwtest-chart');
  13142. if (!canvas) return;
  13143. const ctx = canvas.getContext('2d');
  13144. const dpr = window.devicePixelRatio || 1;
  13145. const width = canvas.width / dpr;
  13146. const height = canvas.height / dpr;
  13147. ctx.clearRect(0, 0, width, height);
  13148. const points = bwtestState.chartPoints;
  13149. if (!points || points.length === 0) return;
  13150. // Determine scale ceiling
  13151. let maxRate = 10;
  13152. for (const p of points) {
  13153. if (p.tx > maxRate) maxRate = p.tx;
  13154. if (p.rx > maxRate) maxRate = p.rx;
  13155. }
  13156. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13157. const paddingLeft = 55;
  13158. const paddingBottom = 24;
  13159. const paddingTop = 12;
  13160. const paddingRight = 16;
  13161. const chartW = width - paddingLeft - paddingRight;
  13162. const chartH = height - paddingTop - paddingBottom;
  13163. // Grid Lines and Y-Axis labels
  13164. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13165. ctx.lineWidth = 1;
  13166. ctx.fillStyle = '#94a3b8';
  13167. ctx.font = '10px monospace';
  13168. ctx.textAlign = 'right';
  13169. const gridSteps = 4;
  13170. for (let i = 0; i <= gridSteps; i++) {
  13171. const val = (maxRate / gridSteps) * i;
  13172. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13173. ctx.beginPath();
  13174. ctx.moveTo(paddingLeft, y);
  13175. ctx.lineTo(width - paddingRight, y);
  13176. ctx.stroke();
  13177. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13178. }
  13179. // Draw TX Line (Cyan #22d3ee)
  13180. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13181. // Draw RX Line (Purple #a855f7)
  13182. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13183. }
  13184. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13185. if (points.length < 2) return;
  13186. const stepX = w / Math.max(points.length - 1, 1);
  13187. // Gradient area fill
  13188. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13189. grad.addColorStop(0, fillColor);
  13190. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13191. ctx.beginPath();
  13192. points.forEach((p, idx) => {
  13193. const x = left + idx * stepX;
  13194. const val = valFn(p);
  13195. const y = top + h - (val / maxVal) * h;
  13196. if (idx === 0) {
  13197. ctx.moveTo(x, y);
  13198. } else {
  13199. ctx.lineTo(x, y);
  13200. }
  13201. });
  13202. // Complete path for fill
  13203. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13204. ctx.lineTo(left, top + h);
  13205. ctx.closePath();
  13206. ctx.fillStyle = grad;
  13207. ctx.fill();
  13208. // Draw line stroke
  13209. ctx.beginPath();
  13210. ctx.lineWidth = 2.5;
  13211. ctx.strokeStyle = strokeColor;
  13212. points.forEach((p, idx) => {
  13213. const x = left + idx * stepX;
  13214. const val = valFn(p);
  13215. const y = top + h - (val / maxVal) * h;
  13216. if (idx === 0) {
  13217. ctx.moveTo(x, y);
  13218. } else {
  13219. ctx.lineTo(x, y);
  13220. }
  13221. });
  13222. ctx.stroke();
  13223. // Draw end point halo
  13224. const lastP = points[points.length - 1];
  13225. const lastX = left + (points.length - 1) * stepX;
  13226. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13227. ctx.fillStyle = strokeColor;
  13228. ctx.beginPath();
  13229. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13230. ctx.fill();
  13231. }
  13232. async function loadBwTestHistory() {
  13233. try {
  13234. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13235. if (!res.ok) return;
  13236. const list = await res.json();
  13237. renderBwTestHistory(Array.isArray(list) ? list : []);
  13238. } catch (err) {
  13239. console.error('Failed to load BwTest history:', err);
  13240. }
  13241. }
  13242. function renderBwTestHistory(list) {
  13243. const tbody = document.getElementById('bwtest-history-tbody');
  13244. if (!tbody) return;
  13245. if (list.length === 0) {
  13246. 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>`;
  13247. return;
  13248. }
  13249. tbody.innerHTML = '';
  13250. list.forEach(item => {
  13251. const s = item.summary || {};
  13252. const tr = document.createElement('tr');
  13253. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13254. const dirBadge = item.direction === 'both'
  13255. ? `<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>`
  13256. : item.direction === 'tx'
  13257. ? `<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>`
  13258. : `<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>`;
  13259. const protoBadge = item.protocol === 'tcp'
  13260. ? `<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>`
  13261. : `<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>`;
  13262. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13263. tr.innerHTML = `
  13264. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13265. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13266. <td class="py-2.5 px-4">${protoBadge}</td>
  13267. <td class="py-2.5 px-4">${dirBadge}</td>
  13268. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13269. <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>
  13270. <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>
  13271. <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>
  13272. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13273. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13274. `;
  13275. tbody.appendChild(tr);
  13276. });
  13277. }