app.js 637 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. // Live polling every 2.5 seconds
  80. setInterval(() => {
  81. if (state.isPolling) {
  82. fetchData(false);
  83. }
  84. }, 2500);
  85. });
  86. // Navigation Handler
  87. function navigate(tabName) {
  88. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  89. navigate('bgp');
  90. return;
  91. }
  92. if (tabName === 'vlans') {
  93. navigate('interfaces');
  94. return;
  95. }
  96. state.activeTab = tabName;
  97. window.location.hash = tabName;
  98. // Update nav links styling
  99. document.querySelectorAll('.nav-link').forEach(link => {
  100. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  101. });
  102. const activeNav = document.getElementById(`nav-${tabName}`);
  103. if (activeNav) {
  104. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  105. }
  106. // Update page headers
  107. const titles = {
  108. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  109. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  110. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  111. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  112. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  113. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  114. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  115. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  116. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  117. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  118. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  119. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  120. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  121. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  122. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  123. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  124. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  125. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  126. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  127. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  128. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  129. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  130. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  131. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  132. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  133. };
  134. const header = titles[tabName] || titles.dashboard;
  135. const pTitle = document.getElementById('page-title');
  136. if (pTitle) pTitle.innerText = header.title;
  137. const pSub = document.getElementById('page-subtitle');
  138. if (pSub) pSub.innerText = header.sub;
  139. // Toggle sections dynamically for all section elements
  140. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  141. if (el.id === `section-${tabName}`) {
  142. el.classList.remove('hidden');
  143. } else {
  144. el.classList.add('hidden');
  145. }
  146. });
  147. if (tabName === 'bridge') loadBridge();
  148. if (tabName === 'firewall') loadFirewall();
  149. if (tabName === 'routes') loadRoutes();
  150. if (tabName === 'bgp') {
  151. loadDynamicRouting();
  152. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  153. }
  154. if (tabName === 'ospf') {
  155. loadDynamicRouting();
  156. switchOspfTab(state.activeOspfTab || 'instances');
  157. }
  158. if (tabName === 'routing-filters') loadDynamicRouting();
  159. if (tabName === 'dynamic-routing') loadDynamicRouting();
  160. if (tabName === 'ppp') loadPPP();
  161. if (tabName === 'eoip') loadEoIP();
  162. if (tabName === 'aerotun') loadAeroTUN();
  163. if (tabName === 'persistence') loadDebianConfig();
  164. if (tabName === 'pppoe') loadPPPoE();
  165. if (tabName === 'wireguard') loadWireGuard();
  166. if (tabName === 'ipsec') loadIPSec();
  167. if (tabName === 'l2tp') loadL2TP();
  168. if (tabName === 'pptp') loadPPTP();
  169. if (tabName === 'tools') loadToolsView();
  170. if (tabName === 'dhcp-client') loadDHCPClients();
  171. if (tabName === 'dhcp-server') loadDHCPServer();
  172. if (tabName === 'vrrp') loadVRRP();
  173. if (tabName === 'bwtest') loadBwTestView();
  174. if (tabName === 'settings') loadSettingsData();
  175. setTimeout(initTableSorting, 50);
  176. }
  177. // Fetch all core system, network and VPN telemetry
  178. async function fetchData(isManual = false) {
  179. const spinner = document.getElementById('refresh-spinner');
  180. if (isManual && spinner) spinner.classList.add('animate-spin');
  181. try {
  182. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  183. fetch(`${API_BASE}/system/status`),
  184. fetch(`${API_BASE}/interfaces`),
  185. fetch(`${API_BASE}/vlans`),
  186. fetch(`${API_BASE}/vpn/status`),
  187. fetch(`${API_BASE}/firewall/summary`),
  188. fetch(`${API_BASE}/routing/dynamic/summary`),
  189. fetch(`${API_BASE}/bridge/summary`),
  190. fetch(`${API_BASE}/dhcp/clients/summary`),
  191. fetch(`${API_BASE}/dhcp/clients`),
  192. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  193. ]);
  194. if (vrrpSumRes && vrrpSumRes.ok) {
  195. state.vrrpSummary = await vrrpSumRes.json();
  196. renderVRRPSummary();
  197. }
  198. if (dhcpSumRes && dhcpSumRes.ok) {
  199. state.dhcpSummary = await dhcpSumRes.json();
  200. const bDhcp = document.getElementById('badge-dhcp-client-count');
  201. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  202. }
  203. if (dhcpClientsRes && dhcpClientsRes.ok) {
  204. state.dhcpClients = await dhcpClientsRes.json();
  205. }
  206. if (brSummaryRes.ok) {
  207. state.bridgeSummary = await brSummaryRes.json();
  208. const bBridge = document.getElementById('badge-bridge-count');
  209. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  210. const sBr = document.getElementById('bridge-stat-bridges');
  211. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  212. const sPorts = document.getElementById('bridge-stat-ports');
  213. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  214. const sHosts = document.getElementById('bridge-stat-hosts');
  215. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  216. }
  217. if (statusRes.ok) state.systemStatus = await statusRes.json();
  218. if (ifacesRes.ok) {
  219. const ifacesData = await ifacesRes.json();
  220. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  221. state.interfaces = rawIfaces.filter(i => {
  222. if (!i.name) return false;
  223. if (i.name.startsWith('ep_')) return false;
  224. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  225. });
  226. try { populateToolsInterfaces(); } catch (e) {}
  227. }
  228. if (vlansRes.ok) {
  229. const vlansData = await vlansRes.json();
  230. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  231. }
  232. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  233. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  234. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  235. updateSystemMetrics();
  236. updateBadges();
  237. if (state.activeTab === 'dashboard') renderDashboard();
  238. if (state.activeTab === 'interfaces') renderInterfacesList();
  239. if (state.activeTab === 'vlans') renderVlansList();
  240. if (state.activeTab === 'firewall') loadFirewall(false);
  241. if (state.activeTab === 'routes') loadRoutes(false);
  242. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  243. if (state.activeTab === 'ppp') loadPPP(false);
  244. if (state.activeTab === 'eoip') loadEoIP(false);
  245. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  246. if (state.activeTab === 'pppoe') loadPPPoE(false);
  247. if (state.activeTab === 'wireguard') loadWireGuard(false);
  248. if (state.activeTab === 'ipsec') loadIPSec(false);
  249. if (state.activeTab === 'l2tp') loadL2TP(false);
  250. if (state.activeTab === 'pptp') loadPPTP(false);
  251. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  252. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  253. if (state.activeTab === 'vrrp') loadVRRP(false);
  254. if (state.activeTab === 'settings') loadSettingsData(false);
  255. fetchBwTestServerStatus();
  256. } catch (err) {
  257. console.error('Failed to fetch router state:', err);
  258. } finally {
  259. if (isManual && spinner) {
  260. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  261. }
  262. }
  263. }
  264. // Update Top KPI and Sidebar Telemetry
  265. function updateSystemMetrics() {
  266. const s = state.systemStatus;
  267. const v = state.vpnStatus;
  268. if (!s) return;
  269. // Sidebar Host & Uptime
  270. const sideHost = document.getElementById('side-hostname');
  271. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  272. const sideUp = document.getElementById('side-uptime');
  273. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  274. const sideGw = document.getElementById('side-gateway-ip');
  275. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  276. // Compute CPU Metrics
  277. let cpuPct = 0;
  278. if (s.cpu_pct !== undefined) {
  279. cpuPct = s.cpu_pct;
  280. } else if (s.cpu_load && s.cpu_load.length > 0) {
  281. const cores = s.cpu_cores || 1;
  282. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  283. }
  284. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  285. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  286. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  287. // Sidebar CPU
  288. const sideCpuVal = document.getElementById('side-cpu-val');
  289. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  290. const sideCpuBar = document.getElementById('side-cpu-bar');
  291. if (sideCpuBar) {
  292. sideCpuBar.style.width = cpuWidth;
  293. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  294. }
  295. // Dashboard CPU Card
  296. const dashCpuVal = document.getElementById('dash-cpu-val');
  297. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  298. const dashCpuBar = document.getElementById('dash-cpu-bar');
  299. if (dashCpuBar) {
  300. dashCpuBar.style.width = cpuWidth;
  301. if (cpuPct > 85) {
  302. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  303. } else if (cpuPct > 65) {
  304. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  305. } else {
  306. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  307. }
  308. }
  309. const dashCpuCores = document.getElementById('dash-cpu-cores');
  310. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  311. const dashCpuLoad = document.getElementById('dash-cpu-load');
  312. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  313. const dashCpuStatus = document.getElementById('dash-cpu-status');
  314. if (dashCpuStatus) {
  315. if (cpuPct > 85) {
  316. dashCpuStatus.innerText = 'High';
  317. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  318. } else if (cpuPct > 65) {
  319. dashCpuStatus.innerText = 'Heavy';
  320. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  321. } else {
  322. dashCpuStatus.innerText = 'Normal';
  323. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  324. }
  325. }
  326. // Compute RAM Metrics
  327. const memPct = Math.round(s.mem_usage_pct || 0);
  328. const memPctStr = `${memPct}%`;
  329. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  330. const usedMB = s.mem_used_mb || 0;
  331. const totalMB = s.mem_total_mb || 0;
  332. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  333. function fmtMemMB(mb) {
  334. if (mb >= 1024) {
  335. return `${(mb / 1024).toFixed(1)} GB`;
  336. }
  337. return `${mb} MB`;
  338. }
  339. // Sidebar RAM
  340. const sideRamVal = document.getElementById('side-ram-val');
  341. if (sideRamVal) sideRamVal.innerText = memPctStr;
  342. const sideRamBar = document.getElementById('side-ram-bar');
  343. if (sideRamBar) sideRamBar.style.width = memWidth;
  344. // Dashboard RAM Card
  345. const dashRamVal = document.getElementById('dash-ram-val');
  346. if (dashRamVal) dashRamVal.innerText = memPctStr;
  347. const dashRamBar = document.getElementById('dash-ram-bar');
  348. if (dashRamBar) {
  349. dashRamBar.style.width = memWidth;
  350. if (memPct > 85) {
  351. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  352. } else if (memPct > 70) {
  353. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  354. } else {
  355. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  356. }
  357. }
  358. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  359. if (dashRamUsedTotal) {
  360. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  361. }
  362. const dashRamFree = document.getElementById('dash-ram-free');
  363. if (dashRamFree) {
  364. dashRamFree.innerText = fmtMemMB(freeMB);
  365. }
  366. const dashRamStatus = document.getElementById('dash-ram-status');
  367. if (dashRamStatus) {
  368. if (memPct > 85) {
  369. dashRamStatus.innerText = 'High';
  370. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  371. } else {
  372. dashRamStatus.innerText = 'Active';
  373. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  374. }
  375. }
  376. // Legacy Dashboard Stats (Safe checks)
  377. const elIfacesUp = document.getElementById('stat-ifaces-up');
  378. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  379. const elIfacesTot = document.getElementById('stat-ifaces-total');
  380. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  381. const elIfacesDown = document.getElementById('stat-ifaces-down');
  382. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  383. const elVlans = document.getElementById('stat-vlans-count');
  384. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  385. // VPN Status Indicators
  386. if (v) {
  387. const totalActive = v.total_active_tunnels || 0;
  388. const statVpnActive = document.getElementById('stat-vpn-active');
  389. if (statVpnActive) statVpnActive.innerText = totalActive;
  390. const tunnelsDot = document.getElementById('tunnels-dot');
  391. const tunnelsLabel = document.getElementById('tunnels-label');
  392. if (tunnelsDot && tunnelsLabel) {
  393. if (totalActive > 0) {
  394. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  395. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  396. } else {
  397. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  398. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  399. }
  400. }
  401. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  402. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  403. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  404. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  405. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  406. }
  407. // Total Live Bandwidth Rate
  408. let totalRx = 0;
  409. let totalTx = 0;
  410. (state.interfaces || []).forEach(i => {
  411. if (i.rate) {
  412. totalRx += i.rate.rx_bytes_sec || 0;
  413. totalTx += i.rate.tx_bytes_sec || 0;
  414. }
  415. });
  416. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  417. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  418. }
  419. function setDotBadge(id, active) {
  420. const el = document.getElementById(id);
  421. if (!el) return;
  422. if (active) {
  423. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  424. } else {
  425. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  426. }
  427. }
  428. function updateBadges() {
  429. const bIfaces = document.getElementById('badge-ifaces-count');
  430. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  431. const bVlans = document.getElementById('badge-vlans-count');
  432. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  433. if (state.fwSummary) {
  434. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  435. const badgeFw = document.getElementById('badge-firewall-count');
  436. if (badgeFw) badgeFw.innerText = totalFwRules;
  437. }
  438. if (state.vpnStatus) {
  439. const v = state.vpnStatus;
  440. const bEoIP = document.getElementById('badge-eoip-count');
  441. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  442. const bAero = document.getElementById('badge-aerotun-count');
  443. if (bAero) bAero.innerText = v.total_aerotun || 0;
  444. const bPPPSess = document.getElementById('badge-ppp-sessions');
  445. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  446. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  447. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  448. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  449. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  450. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  451. }
  452. if (state.dynSummary) {
  453. const d = state.dynSummary;
  454. setDotBadge('badge-bgp-dot', d.bgp_running);
  455. setDotBadge('badge-ospf-dot', d.ospf_running);
  456. const bBgp = document.getElementById('badge-bgp-count');
  457. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  458. const bOspf = document.getElementById('badge-ospf-count');
  459. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  460. const bFilters = document.getElementById('badge-filters-count');
  461. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  462. }
  463. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  464. if (bDhcpServer) {
  465. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  466. }
  467. }
  468. // Render Dashboard View
  469. function renderDashboard() {
  470. const matrix = document.getElementById('port-matrix');
  471. matrix.innerHTML = '';
  472. (state.interfaces || []).forEach(iface => {
  473. const isUp = iface.state === 'UP';
  474. const isVlan = iface.is_vlan;
  475. const portCard = document.createElement('div');
  476. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  477. isUp
  478. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  479. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  480. }`;
  481. portCard.onclick = () => openIfaceModal(iface.name);
  482. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  483. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  484. portCard.innerHTML = `
  485. <div class="flex items-center justify-between mb-2">
  486. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  487. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  488. </div>
  489. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  490. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  491. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  492. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  493. </div>
  494. `;
  495. matrix.appendChild(portCard);
  496. });
  497. const ifaceTbody = document.getElementById('quick-interfaces-table');
  498. if (ifaceTbody) {
  499. ifaceTbody.innerHTML = '';
  500. (state.interfaces || []).forEach(i => {
  501. const isUp = i.state === 'UP';
  502. const tr = document.createElement('tr');
  503. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  504. tr.onclick = () => openIfaceModal(i.name);
  505. const rxStr = i.rate?.rx_human || '0 B/s';
  506. const txStr = i.rate?.tx_human || '0 B/s';
  507. tr.innerHTML = `
  508. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  509. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  510. <span>${i.name}</span>
  511. </td>
  512. <td class="py-2.5 text-slate-300 font-sans">
  513. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  514. </td>
  515. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  516. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  517. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  518. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  519. </td>
  520. <td class="py-2.5 text-right font-sans font-semibold">
  521. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  522. </td>
  523. `;
  524. ifaceTbody.appendChild(tr);
  525. });
  526. }
  527. const vlanTbody = document.getElementById('quick-vlans-table');
  528. if (vlanTbody) {
  529. vlanTbody.innerHTML = '';
  530. }
  531. }
  532. // Expand / Collapse Handlers
  533. function toggleExpand(parentName) {
  534. if (state.expandedParents.has(parentName)) {
  535. state.expandedParents.delete(parentName);
  536. } else {
  537. state.expandedParents.add(parentName);
  538. }
  539. renderInterfacesList();
  540. }
  541. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  542. function supportsVLAN(iface) {
  543. if (!iface) return false;
  544. if (iface.is_vlan) return false;
  545. const name = (iface.name || '').toLowerCase();
  546. const type = (iface.type || '').toLowerCase();
  547. const role = (iface.role || '').toLowerCase();
  548. // Exclude loopback
  549. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  550. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  551. if (type === 'wireguard' || name.startsWith('wg')) return false;
  552. // Exclude PPP / PPPoE
  553. if (type === 'ppp' || name.startsWith('ppp')) return false;
  554. // Exclude other Layer 3 tunnels and dummy devices
  555. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  556. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  557. return false;
  558. }
  559. // If name already contains a dot, it's already a sub-interface
  560. if (name.includes('.')) return false;
  561. return true;
  562. }
  563. // Expand / Collapse Handlers
  564. function toggleExpand(parentName) {
  565. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  566. if (childVlans.length === 0) {
  567. // Cannot expand an interface with no VLANs
  568. state.expandedParents.delete(parentName);
  569. return;
  570. }
  571. if (state.expandedParents.has(parentName)) {
  572. state.expandedParents.delete(parentName);
  573. } else {
  574. state.expandedParents.add(parentName);
  575. }
  576. renderInterfacesList();
  577. }
  578. function expandAllIfaces(expand) {
  579. if (expand) {
  580. (state.interfaces || []).forEach(i => {
  581. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  582. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  583. });
  584. } else {
  585. state.expandedParents.clear();
  586. }
  587. renderInterfacesList();
  588. }
  589. // Filter and Render Hierarchical Interfaces List
  590. function filterIfaces(filter) {
  591. state.ifaceFilter = filter || 'all';
  592. renderInterfacesList();
  593. }
  594. function renderInterfacesList() {
  595. const tbody = document.getElementById('interfaces-tree-tbody');
  596. const emptyState = document.getElementById('interfaces-empty-state');
  597. const summary = document.getElementById('ifaces-list-summary');
  598. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  599. tbody.innerHTML = '';
  600. const allIfaces = state.interfaces || [];
  601. const allVlans = state.vlans || [];
  602. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  603. const filteredParents = parentIfaces.filter(parent => {
  604. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  605. if (query) {
  606. const matchName = parent.name.toLowerCase().includes(query);
  607. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  608. const matchRole = (parent.role || '').toLowerCase().includes(query);
  609. const matchType = (parent.type || '').toLowerCase().includes(query);
  610. const matchVlan = childVlans.some(v =>
  611. v.name.toLowerCase().includes(query) ||
  612. String(v.vlan_id).includes(query) ||
  613. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  614. (v.description || '').toLowerCase().includes(query)
  615. );
  616. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  617. }
  618. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  619. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  620. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  621. return true;
  622. });
  623. if (summary) {
  624. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  625. }
  626. if (filteredParents.length === 0) {
  627. emptyState?.classList.remove('hidden');
  628. return;
  629. }
  630. emptyState?.classList.add('hidden');
  631. filteredParents.forEach(parent => {
  632. const isUp = parent.state === 'UP';
  633. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  634. const hasVlans = childVlans.length > 0;
  635. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  636. const canHaveVlan = supportsVLAN(parent);
  637. const parentRow = document.createElement('tr');
  638. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  639. parentRow.innerHTML = `
  640. <td class="py-3 px-3 text-center">
  641. ${hasVlans ? `
  642. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  643. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  644. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  645. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  646. </svg>
  647. </button>
  648. ` : `
  649. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  650. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  651. </div>
  652. `}
  653. </td>
  654. <td class="py-3 px-4">
  655. <div class="flex items-center space-x-2.5">
  656. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  657. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  658. </div>
  659. <div>
  660. <div class="flex items-center gap-2">
  661. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  662. <span>${parent.name}</span>
  663. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  664. </span>
  665. ${hasVlans ? `
  666. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  667. ` : `
  668. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  669. `}
  670. </div>
  671. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  672. </div>
  673. </div>
  674. </td>
  675. <td class="py-3 px-4 font-sans">
  676. <div class="flex items-center gap-1.5">
  677. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  678. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  679. </div>
  680. </td>
  681. <td class="py-3 px-4">
  682. ${parent.ipv4 && parent.ipv4.length > 0
  683. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  684. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  685. }
  686. ${(() => {
  687. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  688. if (!c) return '';
  689. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  690. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  691. })()}
  692. </td>
  693. <td class="py-3 px-4 text-slate-400 text-[11px]">
  694. <div>${parent.mac || 'N/A'}</div>
  695. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  696. </td>
  697. <td class="py-3 px-4 text-[11px]">
  698. <div class="flex items-center space-x-2">
  699. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  700. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  701. </div>
  702. </td>
  703. <td class="py-3 px-4 font-sans">
  704. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  705. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  706. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  707. }" title="Click to toggle link status">
  708. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  709. <span>${parent.state}</span>
  710. </button>
  711. </td>
  712. <td class="py-3 px-4 text-right space-x-2 font-sans">
  713. ${(() => {
  714. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  715. if (c) {
  716. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  717. }
  718. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  719. })()}
  720. ${canHaveVlan ? `
  721. <button onclick="openVlanModal('${parent.name}')"
  722. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  723. + Add VLAN
  724. </button>
  725. ` : ''}
  726. <button onclick="openIfaceModal('${parent.name}')"
  727. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  728. Configure
  729. </button>
  730. </td>
  731. `;
  732. tbody.appendChild(parentRow);
  733. if (isExpanded) {
  734. const drawerRow = document.createElement('tr');
  735. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  736. const drawerCell = document.createElement('td');
  737. drawerCell.colSpan = 8;
  738. drawerCell.className = 'p-0';
  739. drawerCell.innerHTML = `
  740. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  741. <div class="flex items-center justify-between mb-3">
  742. <div class="flex items-center space-x-3">
  743. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  744. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  745. </span>
  746. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  747. ${childVlans.length} Attached
  748. </span>
  749. </div>
  750. <button onclick="openVlanModal('${parent.name}')"
  751. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  752. <span>+ Create VLAN on ${parent.name}</span>
  753. </button>
  754. </div>
  755. ${childVlans.length === 0 ? `
  756. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  757. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  758. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  759. <span>+ Create Your First VLAN on ${parent.name}</span>
  760. </button>
  761. </div>
  762. ` : `
  763. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  764. <table class="w-full text-left text-xs font-mono">
  765. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  766. <tr>
  767. <th class="py-2.5 px-4">VLAN ID</th>
  768. <th class="py-2.5 px-4">Interface Device</th>
  769. <th class="py-2.5 px-4">Subnet Gateway</th>
  770. <th class="py-2.5 px-4">Role / Alias</th>
  771. <th class="py-2.5 px-4">MTU</th>
  772. <th class="py-2.5 px-4">Throughput</th>
  773. <th class="py-2.5 px-4">Status</th>
  774. <th class="py-2.5 px-4 text-right">Actions</th>
  775. </tr>
  776. </thead>
  777. <tbody class="divide-y divide-slate-800/70">
  778. ${childVlans.map(v => {
  779. const isVlanUp = v.state === 'UP';
  780. return `
  781. <tr class="hover:bg-slate-800/40 transition">
  782. <td class="py-2.5 px-4">
  783. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  784. VLAN ${v.vlan_id}
  785. </span>
  786. </td>
  787. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  788. <span class="text-cyan-500">└─</span>
  789. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  790. <span>${v.name}</span>
  791. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  792. </span>
  793. </td>
  794. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  795. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  796. ${(() => {
  797. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  798. if (!c) return '';
  799. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  800. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  801. })()}
  802. </td>
  803. <td class="py-2.5 px-4 font-sans text-slate-300">
  804. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  805. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  806. </td>
  807. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  808. <td class="py-2.5 px-4 text-[11px]">
  809. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  810. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  811. </td>
  812. <td class="py-2.5 px-4 font-sans">
  813. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  814. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  815. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  816. }">
  817. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  818. <span>${v.state}</span>
  819. </button>
  820. </td>
  821. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  822. ${(() => {
  823. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  824. if (c) {
  825. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  826. }
  827. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  828. })()}
  829. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  830. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  831. </td>
  832. </tr>
  833. `;
  834. }).join('')}
  835. </tbody>
  836. </table>
  837. </div>
  838. `}
  839. </div>
  840. `;
  841. drawerRow.appendChild(drawerCell);
  842. tbody.appendChild(drawerRow);
  843. }
  844. });
  845. }
  846. // Render VLANs Dedicated View
  847. function renderVlansList() {
  848. const tbody = document.getElementById('vlans-table-body');
  849. if (!tbody) return;
  850. const emptyState = document.getElementById('vlans-empty-state');
  851. const countBadge = document.getElementById('vlans-table-count');
  852. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  853. tbody.innerHTML = '';
  854. const allVlans = state.vlans || [];
  855. if (countBadge) countBadge.innerText = allVlans.length;
  856. const filtered = allVlans.filter(v => {
  857. if (!query) return true;
  858. return v.name.toLowerCase().includes(query) ||
  859. String(v.vlan_id).includes(query) ||
  860. (v.description || '').toLowerCase().includes(query) ||
  861. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  862. });
  863. if (allVlans.length === 0) {
  864. emptyState.classList.remove('hidden');
  865. return;
  866. }
  867. emptyState.classList.add('hidden');
  868. filtered.forEach(v => {
  869. const isUp = v.state === 'UP';
  870. const tr = document.createElement('tr');
  871. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  872. tr.innerHTML = `
  873. <td class="py-3 px-4">
  874. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  875. VLAN ${v.vlan_id}
  876. </span>
  877. </td>
  878. <td class="py-3 px-4 font-bold text-white">
  879. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  880. <span>${v.name}</span>
  881. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  882. </span>
  883. </td>
  884. <td class="py-3 px-4 text-slate-300">
  885. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  886. </td>
  887. <td class="py-3 px-4 text-emerald-400 font-medium">
  888. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  889. </td>
  890. <td class="py-3 px-4 text-slate-300 font-sans">
  891. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  892. </td>
  893. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  894. <td class="py-3 px-4 font-sans">
  895. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  896. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  897. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  898. }">
  899. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  900. <span>${v.state}</span>
  901. </button>
  902. </td>
  903. <td class="py-3 px-4 text-right space-x-2 font-sans">
  904. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  905. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  906. </td>
  907. `;
  908. tbody.appendChild(tr);
  909. });
  910. }
  911. // Toggle interface UP / DOWN
  912. async function toggleInterfaceState(name, newState) {
  913. try {
  914. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  915. method: 'POST',
  916. headers: { 'Content-Type': 'application/json' },
  917. body: JSON.stringify({ state: newState })
  918. });
  919. const data = await res.json();
  920. if (res.ok) {
  921. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  922. fetchData(false);
  923. } else {
  924. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  925. }
  926. } catch (err) {
  927. showToast('Error', err.message, 'error');
  928. }
  929. }
  930. // ---------------- MikroTik Flag & Utilities ----------------
  931. function renderMikroTikFlag(running, disabled) {
  932. if (running) {
  933. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  934. }
  935. if (disabled) {
  936. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  937. }
  938. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  939. }
  940. function copyToClipboard(text, label = 'Text') {
  941. navigator.clipboard.writeText(text).then(() => {
  942. showToast('Copied', `${label} copied to clipboard`, 'success');
  943. }).catch(() => {
  944. prompt('Copy value:', text);
  945. });
  946. }
  947. // ======================== PPP Profiles Shared Helper ========================
  948. async function fetchPPPProfilesList() {
  949. try {
  950. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  951. if (res.ok) {
  952. state.pppProfiles = await res.json();
  953. }
  954. } catch (err) {
  955. console.error('Failed to load PPP profiles:', err);
  956. }
  957. }
  958. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  959. const sel = document.getElementById(selectId);
  960. if (!sel) return;
  961. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  962. { name: 'default', use_encryption: 'no' },
  963. { name: 'default-encryption', use_encryption: 'required' }
  964. ];
  965. sel.innerHTML = '';
  966. profiles.forEach(p => {
  967. const opt = document.createElement('option');
  968. opt.value = p.name;
  969. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  970. opt.innerText = `${p.name}${encBadge}`;
  971. sel.appendChild(opt);
  972. });
  973. if (selectedVal) {
  974. sel.value = selectedVal;
  975. } else {
  976. sel.value = defaultVal;
  977. }
  978. if (!sel.value && sel.options.length > 0) {
  979. sel.selectedIndex = 0;
  980. }
  981. }
  982. // ======================== PPPoE Multi-Instance ========================
  983. async function loadPPPoE(populateInputs = true) {
  984. try {
  985. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  986. await fetchPPPProfilesList();
  987. }
  988. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  989. const list = await res.json();
  990. state.pppoeList = Array.isArray(list) ? list : [];
  991. const badge = document.getElementById('pppoe-count-badge');
  992. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  993. const tbody = document.getElementById('pppoe-table-body');
  994. const empty = document.getElementById('pppoe-empty');
  995. if (!tbody) return;
  996. tbody.innerHTML = '';
  997. if (state.pppoeList.length === 0) {
  998. if (empty) empty.classList.remove('hidden');
  999. } else {
  1000. if (empty) empty.classList.add('hidden');
  1001. state.pppoeList.forEach(inst => {
  1002. const tr = document.createElement('tr');
  1003. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1004. tr.innerHTML = `
  1005. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1006. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1007. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1008. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1009. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1010. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1011. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1012. <td class="py-2.5 px-3 text-center">
  1013. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1014. ${inst.default_route ? 'Yes' : 'No'}
  1015. </span>
  1016. </td>
  1017. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1018. ${inst.running ? `
  1019. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1020. ` : `
  1021. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1022. `}
  1023. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1024. ${inst.disabled ? 'Enable' : 'Disable'}
  1025. </button>
  1026. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1027. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1028. </td>
  1029. `;
  1030. tbody.appendChild(tr);
  1031. });
  1032. }
  1033. } catch (err) {
  1034. console.error('Failed to load PPPoE:', err);
  1035. }
  1036. }
  1037. function openAddPPPoEModal() {
  1038. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1039. document.getElementById('pppoe-modal-edit-orig').value = '';
  1040. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1041. document.getElementById('pppoe-modal-name').readOnly = false;
  1042. document.getElementById('pppoe-modal-user').value = '';
  1043. document.getElementById('pppoe-modal-pass').value = '';
  1044. document.getElementById('pppoe-modal-service').value = '';
  1045. document.getElementById('pppoe-modal-mtu').value = '1492';
  1046. document.getElementById('pppoe-modal-defroute').checked = true;
  1047. document.getElementById('pppoe-modal-reconnect').checked = true;
  1048. document.getElementById('pppoe-modal-disabled').checked = false;
  1049. // Populate profiles
  1050. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1051. // Populate interfaces
  1052. const sel = document.getElementById('pppoe-modal-iface');
  1053. sel.innerHTML = '';
  1054. (state.interfaces || []).forEach(i => {
  1055. if (i.name === 'lo') return;
  1056. const opt = document.createElement('option');
  1057. opt.value = i.name;
  1058. opt.innerText = `${i.name} (${i.role || i.type})`;
  1059. sel.appendChild(opt);
  1060. });
  1061. document.getElementById('pppoe-modal').classList.remove('hidden');
  1062. }
  1063. function openEditPPPoEModal(name) {
  1064. const inst = (state.pppoeList || []).find(i => i.name === name);
  1065. if (!inst) return;
  1066. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1067. document.getElementById('pppoe-modal-edit-orig').value = name;
  1068. document.getElementById('pppoe-modal-name').value = inst.name;
  1069. document.getElementById('pppoe-modal-name').readOnly = true;
  1070. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1071. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1072. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1073. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1074. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1075. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1076. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1077. // Populate profiles
  1078. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1079. const sel = document.getElementById('pppoe-modal-iface');
  1080. sel.innerHTML = '';
  1081. (state.interfaces || []).forEach(i => {
  1082. if (i.name === 'lo') return;
  1083. const opt = document.createElement('option');
  1084. opt.value = i.name;
  1085. opt.innerText = `${i.name} (${i.role || i.type})`;
  1086. if (i.name === inst.interface) opt.selected = true;
  1087. sel.appendChild(opt);
  1088. });
  1089. document.getElementById('pppoe-modal').classList.remove('hidden');
  1090. }
  1091. function closePPPoEModal() {
  1092. document.getElementById('pppoe-modal').classList.add('hidden');
  1093. }
  1094. async function submitSavePPPoE(e) {
  1095. e.preventDefault();
  1096. const name = document.getElementById('pppoe-modal-name').value.trim();
  1097. const iface = document.getElementById('pppoe-modal-iface').value;
  1098. const user = document.getElementById('pppoe-modal-user').value.trim();
  1099. const pass = document.getElementById('pppoe-modal-pass').value;
  1100. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1101. const service = document.getElementById('pppoe-modal-service').value.trim();
  1102. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1103. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1104. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1105. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1106. try {
  1107. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1108. method: 'POST',
  1109. headers: { 'Content-Type': 'application/json' },
  1110. body: JSON.stringify({
  1111. name,
  1112. interface: iface,
  1113. username: user,
  1114. password: pass,
  1115. profile: profile,
  1116. service_name: service,
  1117. mtu,
  1118. default_route: defRoute,
  1119. auto_reconnect: reconnect,
  1120. disabled
  1121. })
  1122. });
  1123. if (res.ok) {
  1124. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1125. closePPPoEModal();
  1126. loadPPPoE(false);
  1127. fetchData(false);
  1128. } else {
  1129. const err = await res.json();
  1130. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. async function connectPPPoEInstance(name) {
  1137. try {
  1138. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1139. if (res.ok) {
  1140. showToast('Connecting', `Dialing ${name}...`, 'info');
  1141. setTimeout(() => loadPPPoE(false), 2000);
  1142. }
  1143. } catch (err) {
  1144. showToast('Error', err.message, 'error');
  1145. }
  1146. }
  1147. async function disconnectPPPoEInstance(name) {
  1148. try {
  1149. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1150. if (res.ok) {
  1151. showToast('Disconnected', `${name} session terminated`, 'info');
  1152. setTimeout(() => loadPPPoE(false), 1000);
  1153. }
  1154. } catch (err) {
  1155. showToast('Error', err.message, 'error');
  1156. }
  1157. }
  1158. async function togglePPPoEState(name, enable) {
  1159. try {
  1160. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1161. method: 'POST',
  1162. headers: { 'Content-Type': 'application/json' },
  1163. body: JSON.stringify({ enabled: enable })
  1164. });
  1165. if (res.ok) {
  1166. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1167. loadPPPoE(false);
  1168. }
  1169. } catch (err) {
  1170. showToast('Error', err.message, 'error');
  1171. }
  1172. }
  1173. async function deletePPPoEInstance(name) {
  1174. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1175. try {
  1176. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1177. if (res.ok) {
  1178. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1179. loadPPPoE(false);
  1180. fetchData(false);
  1181. }
  1182. } catch (err) {
  1183. showToast('Error', err.message, 'error');
  1184. }
  1185. }
  1186. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1187. state.wgSubTab = 'ifaces';
  1188. function switchWGSubTab(tab) {
  1189. state.wgSubTab = tab;
  1190. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1191. const peersPanel = document.getElementById('wg-subtab-peers');
  1192. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1193. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1194. if (tab === 'ifaces') {
  1195. ifacesPanel?.classList.remove('hidden');
  1196. peersPanel?.classList.add('hidden');
  1197. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1198. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1199. } else {
  1200. ifacesPanel?.classList.add('hidden');
  1201. peersPanel?.classList.remove('hidden');
  1202. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1203. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1204. renderWGPeers();
  1205. }
  1206. }
  1207. async function loadWireGuard(populateInputs = true) {
  1208. try {
  1209. const [ifacesRes, peersRes] = await Promise.all([
  1210. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1211. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1212. ]);
  1213. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1214. const peers = peersRes.ok ? await peersRes.json() : [];
  1215. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1216. state.wgPeers = Array.isArray(peers) ? peers : [];
  1217. // Badges
  1218. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1219. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1220. const peersCountBadge = document.getElementById('wg-peers-count');
  1221. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1222. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1223. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1224. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1225. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1226. // Render Interfaces
  1227. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1228. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1229. if (ifacesTbody) {
  1230. ifacesTbody.innerHTML = '';
  1231. if (state.wgInterfaces.length === 0) {
  1232. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1233. } else {
  1234. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1235. state.wgInterfaces.forEach(iface => {
  1236. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1237. const tr = document.createElement('tr');
  1238. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1239. tr.innerHTML = `
  1240. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1241. <td class="py-2.5 px-3">
  1242. <div class="flex items-center gap-1.5">
  1243. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1244. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1245. </div>
  1246. </td>
  1247. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1248. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1249. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1250. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1251. ${(iface.public_key || '').substring(0, 10)}... 📋
  1252. </span>
  1253. </td>
  1254. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1255. <td class="py-2.5 px-3 text-center">
  1256. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1257. </td>
  1258. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1259. ${iface.running ? `
  1260. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1261. ` : `
  1262. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1263. `}
  1264. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1265. ${iface.disabled ? 'Enable' : 'Disable'}
  1266. </button>
  1267. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1268. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1269. </td>
  1270. `;
  1271. ifacesTbody.appendChild(tr);
  1272. });
  1273. }
  1274. }
  1275. // Populate filter dropdown in peers tab
  1276. const filterSel = document.getElementById('wg-peers-filter-iface');
  1277. if (filterSel) {
  1278. const currentVal = filterSel.value;
  1279. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1280. state.wgInterfaces.forEach(i => {
  1281. const opt = document.createElement('option');
  1282. opt.value = i.name;
  1283. opt.innerText = i.name;
  1284. if (i.name === currentVal) opt.selected = true;
  1285. filterSel.appendChild(opt);
  1286. });
  1287. }
  1288. renderWGPeers();
  1289. } catch (err) {
  1290. console.error('Failed to load WireGuard:', err);
  1291. }
  1292. }
  1293. function renderWGPeers() {
  1294. const filterSel = document.getElementById('wg-peers-filter-iface');
  1295. const selectedIface = filterSel ? filterSel.value : '';
  1296. const tbody = document.getElementById('wg-peers-table-body');
  1297. const empty = document.getElementById('wg-peers-empty');
  1298. if (!tbody) return;
  1299. tbody.innerHTML = '';
  1300. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1301. if (filtered.length === 0) {
  1302. if (empty) empty.classList.remove('hidden');
  1303. } else {
  1304. if (empty) empty.classList.add('hidden');
  1305. filtered.forEach(p => {
  1306. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1307. const tr = document.createElement('tr');
  1308. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1309. tr.innerHTML = `
  1310. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1311. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1312. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1313. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1314. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1315. ${(p.public_key || '').substring(0, 10)}... 📋
  1316. </span>
  1317. </td>
  1318. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1319. <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>
  1320. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1321. <td class="py-2.5 px-3 font-mono text-[11px]">
  1322. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1323. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1324. </td>
  1325. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1326. <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">
  1327. ${p.disabled ? 'Enable' : 'Disable'}
  1328. </button>
  1329. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1330. <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>
  1331. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1332. </td>
  1333. `;
  1334. tbody.appendChild(tr);
  1335. });
  1336. }
  1337. }
  1338. function openAddWGInterfaceModal() {
  1339. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1340. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1341. const nameEl = document.getElementById('wg-iface-modal-name');
  1342. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1343. nameEl.readOnly = false;
  1344. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1345. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1346. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1347. document.getElementById('wg-iface-modal-comment').value = '';
  1348. document.getElementById('wg-iface-modal-pubkey').value = '';
  1349. document.getElementById('wg-iface-modal-privkey').value = '';
  1350. document.getElementById('wg-iface-modal-disabled').checked = false;
  1351. generateWGInterfaceKeys();
  1352. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1353. }
  1354. function openEditWGInterfaceModal(name) {
  1355. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1356. if (!iface) return;
  1357. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1358. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1359. const nameEl = document.getElementById('wg-iface-modal-name');
  1360. nameEl.value = iface.name;
  1361. nameEl.readOnly = false; // ALLOW RENAMING
  1362. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1363. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1364. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1365. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1366. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1367. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1368. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1369. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1370. }
  1371. function closeAddWGInterfaceModal() {
  1372. document.getElementById('wg-iface-modal').classList.add('hidden');
  1373. }
  1374. async function generateWGInterfaceKeys() {
  1375. try {
  1376. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1377. const keys = await res.json();
  1378. if (res.ok) {
  1379. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1380. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1381. }
  1382. } catch (err) {
  1383. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1384. }
  1385. }
  1386. async function onWGInterfacePrivKeyInput() {
  1387. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1388. if (!privKey) return;
  1389. try {
  1390. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1391. method: 'POST',
  1392. headers: { 'Content-Type': 'application/json' },
  1393. body: JSON.stringify({ private_key: privKey })
  1394. });
  1395. if (res.ok) {
  1396. const data = await res.json();
  1397. if (data.public_key) {
  1398. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1399. }
  1400. }
  1401. } catch (err) {
  1402. // Ignore while typing
  1403. }
  1404. }
  1405. function toggleWGPrivKeyVisibility() {
  1406. const el = document.getElementById('wg-iface-modal-privkey');
  1407. const btn = document.getElementById('btn-toggle-wg-privkey');
  1408. if (el.type === 'password') {
  1409. el.type = 'text';
  1410. btn.innerText = '🙈 Hide';
  1411. } else {
  1412. el.type = 'password';
  1413. btn.innerText = '👁️ Show';
  1414. }
  1415. }
  1416. function copyWGInterfacePubKey() {
  1417. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1418. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1419. }
  1420. async function submitSaveWGInterface(e) {
  1421. e.preventDefault();
  1422. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1423. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1424. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1425. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1426. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1427. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1428. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1429. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1430. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1431. try {
  1432. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1433. method: 'POST',
  1434. headers: { 'Content-Type': 'application/json' },
  1435. body: JSON.stringify({
  1436. orig_name: origName,
  1437. name,
  1438. listen_port: port,
  1439. address: addr,
  1440. mtu,
  1441. comment,
  1442. public_key: pub,
  1443. private_key: priv,
  1444. disabled
  1445. })
  1446. });
  1447. const data = await res.json();
  1448. if (res.ok) {
  1449. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1450. closeAddWGInterfaceModal();
  1451. loadWireGuard(false);
  1452. fetchData(false);
  1453. } else {
  1454. showToast('Error', data.error || 'Failed to save interface', 'error');
  1455. }
  1456. } catch (err) {
  1457. showToast('Error', err.message, 'error');
  1458. }
  1459. }
  1460. async function startWGInterface(name) {
  1461. try {
  1462. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1463. if (res.ok) {
  1464. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1465. loadWireGuard(false);
  1466. fetchData(false);
  1467. }
  1468. } catch (err) {
  1469. showToast('Error', err.message, 'error');
  1470. }
  1471. }
  1472. async function stopWGInterface(name) {
  1473. try {
  1474. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1475. if (res.ok) {
  1476. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1477. loadWireGuard(false);
  1478. fetchData(false);
  1479. }
  1480. } catch (err) {
  1481. showToast('Error', err.message, 'error');
  1482. }
  1483. }
  1484. async function toggleWGInterfaceState(name, enable) {
  1485. try {
  1486. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1487. method: 'POST',
  1488. headers: { 'Content-Type': 'application/json' },
  1489. body: JSON.stringify({ enabled: enable })
  1490. });
  1491. if (res.ok) {
  1492. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1493. loadWireGuard(false);
  1494. fetchData(false);
  1495. }
  1496. } catch (err) {
  1497. showToast('Error', err.message, 'error');
  1498. }
  1499. }
  1500. async function deleteWGInterface(name) {
  1501. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1502. try {
  1503. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1504. if (res.ok) {
  1505. showToast('Deleted', `Interface ${name} removed`, 'success');
  1506. loadWireGuard(false);
  1507. fetchData(false);
  1508. }
  1509. } catch (err) {
  1510. showToast('Error', err.message, 'error');
  1511. }
  1512. }
  1513. function populateWGPeerIfaceSelect(selectedIface = '') {
  1514. const sel = document.getElementById('wg-peer-modal-iface');
  1515. if (!sel) return;
  1516. sel.innerHTML = '';
  1517. (state.wgInterfaces || []).forEach(i => {
  1518. const opt = document.createElement('option');
  1519. opt.value = i.name;
  1520. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1521. if (i.name === selectedIface) opt.selected = true;
  1522. sel.appendChild(opt);
  1523. });
  1524. }
  1525. function openAddWGPeerModal() {
  1526. if ((state.wgInterfaces || []).length === 0) {
  1527. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1528. openAddWGInterfaceModal();
  1529. return;
  1530. }
  1531. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1532. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1533. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1534. populateWGPeerIfaceSelect();
  1535. document.getElementById('wg-peer-modal-name').value = '';
  1536. document.getElementById('wg-peer-modal-pubkey').value = '';
  1537. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1538. document.getElementById('wg-peer-modal-endpoint').value = '';
  1539. document.getElementById('wg-peer-modal-port').value = '';
  1540. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1541. document.getElementById('wg-peer-modal-preshared').value = '';
  1542. document.getElementById('wg-peer-modal-disabled').checked = false;
  1543. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1544. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1545. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1546. }
  1547. function openEditWGPeerModal(ifaceName, pubKey) {
  1548. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1549. if (!peer) {
  1550. showToast('Not Found', 'Peer not found', 'warning');
  1551. return;
  1552. }
  1553. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1554. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1555. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1556. populateWGPeerIfaceSelect(peer.interface);
  1557. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1558. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1559. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1560. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1561. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1562. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1563. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1564. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1565. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1566. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1567. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1568. }
  1569. function closeAddWGPeerModal() {
  1570. document.getElementById('wg-peer-modal').classList.add('hidden');
  1571. }
  1572. async function generatePeerKeypairHelper() {
  1573. try {
  1574. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1575. const keys = await res.json();
  1576. if (res.ok) {
  1577. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1578. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1579. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1580. checkWGPeerKeyValidity();
  1581. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1582. }
  1583. } catch (err) {
  1584. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1585. }
  1586. }
  1587. function copyGeneratedPeerPrivKey() {
  1588. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1589. if (priv) copyToClipboard(priv, 'Client Private Key');
  1590. }
  1591. async function generatePeerPSK() {
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1594. const keys = await res.json();
  1595. if (res.ok && keys.private_key) {
  1596. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1597. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1598. }
  1599. } catch (err) {
  1600. showToast('Error', err.message, 'error');
  1601. }
  1602. }
  1603. function checkWGPeerKeyValidity() {
  1604. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1605. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1606. const warningEl = document.getElementById('wg-peer-key-warning');
  1607. if (!warningEl) return;
  1608. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1609. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1610. warningEl.classList.remove('hidden');
  1611. } else {
  1612. warningEl.classList.add('hidden');
  1613. }
  1614. }
  1615. async function submitSaveWGPeer(e) {
  1616. e.preventDefault();
  1617. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1618. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1619. const iface = document.getElementById('wg-peer-modal-iface').value;
  1620. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1621. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1622. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1623. .split(',')
  1624. .map(s => s.trim())
  1625. .filter(s => s.length > 0);
  1626. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1627. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1628. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1629. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1630. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1631. // Validation
  1632. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1633. if (targetIface && targetIface.public_key === pub) {
  1634. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1635. return;
  1636. }
  1637. try {
  1638. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1639. method: 'POST',
  1640. headers: { 'Content-Type': 'application/json' },
  1641. body: JSON.stringify({
  1642. orig_interface: origIface,
  1643. orig_public_key: origPubKey,
  1644. interface: iface,
  1645. name,
  1646. public_key: pub,
  1647. allowed_ips: allowed,
  1648. endpoint_address: epHost,
  1649. endpoint_port: epPort,
  1650. persistent_keepalive: keepalive,
  1651. preshared_key: psk,
  1652. disabled
  1653. })
  1654. });
  1655. const data = await res.json();
  1656. if (res.ok) {
  1657. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1658. closeAddWGPeerModal();
  1659. loadWireGuard(false);
  1660. } else {
  1661. showToast('Error', data.error || 'Failed to save peer', 'error');
  1662. }
  1663. } catch (err) {
  1664. showToast('Error', err.message, 'error');
  1665. }
  1666. }
  1667. async function toggleWGPeerState(iface, pubkey, enable) {
  1668. try {
  1669. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1670. method: 'POST',
  1671. headers: { 'Content-Type': 'application/json' },
  1672. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1673. });
  1674. const data = await res.json();
  1675. if (res.ok) {
  1676. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1677. loadWireGuard(false);
  1678. } else {
  1679. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1680. }
  1681. } catch (err) {
  1682. showToast('Error', err.message, 'error');
  1683. }
  1684. }
  1685. async function deleteWGPeer(iface, pubkey) {
  1686. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1687. try {
  1688. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1689. method: 'POST',
  1690. headers: { 'Content-Type': 'application/json' },
  1691. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1692. });
  1693. const data = await res.json();
  1694. if (res.ok) {
  1695. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1696. loadWireGuard(false);
  1697. } else {
  1698. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1699. }
  1700. } catch (err) {
  1701. showToast('Error', err.message, 'error');
  1702. }
  1703. }
  1704. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1705. function switchIpsecModalTab(tab) {
  1706. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1707. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1708. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1709. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1710. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1711. if (tab === 'p1') {
  1712. if (p1Tab) {
  1713. 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';
  1714. }
  1715. if (p2Tab) {
  1716. 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';
  1717. }
  1718. if (p1Content) p1Content.classList.remove('hidden');
  1719. if (p2Content) p2Content.classList.add('hidden');
  1720. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1721. } else {
  1722. if (p1Tab) {
  1723. 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';
  1724. }
  1725. if (p2Tab) {
  1726. 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';
  1727. }
  1728. if (p1Content) p1Content.classList.add('hidden');
  1729. if (p2Content) p2Content.classList.remove('hidden');
  1730. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1731. }
  1732. }
  1733. function toggleIpsecPhaseStep() {
  1734. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1735. if (p1Content && !p1Content.classList.contains('hidden')) {
  1736. switchIpsecModalTab('p2');
  1737. } else {
  1738. switchIpsecModalTab('p1');
  1739. }
  1740. }
  1741. function toggleIpsecPskVisibility() {
  1742. const pskInput = document.getElementById('ipsec-modal-psk');
  1743. if (!pskInput) return;
  1744. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1745. }
  1746. function addIpsecLocalSubnet(val = '') {
  1747. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1748. if (!container) return;
  1749. const row = document.createElement('div');
  1750. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1751. row.innerHTML = `
  1752. <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">
  1753. <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>
  1754. `;
  1755. container.appendChild(row);
  1756. }
  1757. function addIpsecRemoteSubnet(val = '') {
  1758. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1759. if (!container) return;
  1760. const row = document.createElement('div');
  1761. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1762. row.innerHTML = `
  1763. <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">
  1764. <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>
  1765. `;
  1766. container.appendChild(row);
  1767. }
  1768. function updateIpsecEspProposalFromPFS(val) {
  1769. const prop = document.getElementById('ipsec-modal-espprop');
  1770. if (!prop) return;
  1771. if (val === 'none') {
  1772. prop.value = 'aes256-sha256,aes128-sha256,default';
  1773. } else {
  1774. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1775. }
  1776. }
  1777. function updateIpsecIkeProposalFromDH(dh) {
  1778. const el = document.getElementById('ipsec-modal-ikeprop');
  1779. if (el) {
  1780. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1781. }
  1782. }
  1783. function safeSetVal(id, val) {
  1784. const el = document.getElementById(id);
  1785. if (el) el.value = val;
  1786. }
  1787. function safeSetChecked(id, val) {
  1788. const el = document.getElementById(id);
  1789. if (el) el.checked = !!val;
  1790. }
  1791. function safeGetVal(id, def = '') {
  1792. const el = document.getElementById(id);
  1793. return el ? el.value : def;
  1794. }
  1795. async function loadIPSec(populateInputs = true) {
  1796. try {
  1797. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1798. const list = await res.json();
  1799. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1800. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1801. const badge = document.getElementById('ipsec-sas-badge');
  1802. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1803. const tbody = document.getElementById('ipsec-table-body');
  1804. const empty = document.getElementById('ipsec-empty');
  1805. if (!tbody) return;
  1806. tbody.innerHTML = '';
  1807. if (state.ipsecTunnels.length === 0) {
  1808. if (empty) empty.classList.remove('hidden');
  1809. } else {
  1810. if (empty) empty.classList.add('hidden');
  1811. state.ipsecTunnels.forEach(c => {
  1812. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1813. const tr = document.createElement('tr');
  1814. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1815. // Local subnets tags
  1816. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1817. 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('');
  1818. // Remote subnets tags
  1819. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1820. 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('');
  1821. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1822. const p2Name = c.phase2_name || `${c.name}_p2`;
  1823. tr.innerHTML = `
  1824. <td class="py-2.5 px-3 text-center">
  1825. ${isEstablished ? `
  1826. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1827. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1828. <span>UP</span>
  1829. </span>
  1830. ` : (c.disabled ? `
  1831. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1832. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1833. <span>DOWN</span>
  1834. </span>
  1835. ` : `
  1836. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1837. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1838. <span>IDLE</span>
  1839. </span>
  1840. `)}
  1841. </td>
  1842. <td class="py-2.5 px-4 font-bold text-white">
  1843. <div class="flex items-center gap-2">
  1844. <span class="text-amber-400">🛡</span>
  1845. <div>
  1846. <div>${escapeHtml(c.name)}</div>
  1847. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1848. </div>
  1849. </div>
  1850. </td>
  1851. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1852. <td class="py-2.5 px-4 font-sans">
  1853. <div class="flex items-center gap-1.5">
  1854. <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>
  1855. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1856. </div>
  1857. </td>
  1858. <td class="py-2.5 px-4">
  1859. <div class="space-y-1">
  1860. <div class="flex items-center flex-wrap gap-1">
  1861. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1862. ${localBadges}
  1863. </div>
  1864. <div class="flex items-center flex-wrap gap-1">
  1865. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1866. ${remoteBadges}
  1867. </div>
  1868. </div>
  1869. </td>
  1870. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1871. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1872. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1873. </div>
  1874. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1875. </td>
  1876. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1877. ${isEstablished ? `
  1878. <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>
  1879. ` : `
  1880. <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>
  1881. `}
  1882. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1883. ${c.disabled ? 'Enable' : 'Disable'}
  1884. </button>
  1885. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1886. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1887. </td>
  1888. `;
  1889. tbody.appendChild(tr);
  1890. });
  1891. }
  1892. } catch (err) {
  1893. console.error('Failed to load IPSec:', err);
  1894. }
  1895. }
  1896. function openAddIPSecModal() {
  1897. const modal = document.getElementById('ipsec-modal');
  1898. if (!modal) return;
  1899. const title = document.getElementById('ipsec-modal-title');
  1900. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1901. // Phase 1 Fields
  1902. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1903. const nameEl = document.getElementById('ipsec-modal-name');
  1904. if (nameEl) nameEl.readOnly = false;
  1905. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1906. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1907. safeSetVal('ipsec-modal-remotegw', '');
  1908. safeSetVal('ipsec-modal-localaddrs', '');
  1909. safeSetVal('ipsec-modal-comments', '');
  1910. safeSetVal('ipsec-modal-psk', '');
  1911. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1912. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1913. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1914. safeSetVal('ipsec-modal-localid', '');
  1915. safeSetVal('ipsec-modal-remoteid', '');
  1916. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1917. // Phase 2 Fields
  1918. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1919. safeSetVal('ipsec-modal-espkeylife', '28800');
  1920. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1921. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1922. safeSetChecked('ipsec-modal-autostart', true);
  1923. safeSetChecked('ipsec-modal-disabled', false);
  1924. // Clear & Populate default dynamic subnets
  1925. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1926. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1927. if (localContainer) {
  1928. localContainer.innerHTML = '';
  1929. addIpsecLocalSubnet('192.168.10.0/24');
  1930. }
  1931. if (remoteContainer) {
  1932. remoteContainer.innerHTML = '';
  1933. addIpsecRemoteSubnet('192.168.20.0/24');
  1934. }
  1935. switchIpsecModalTab('p1');
  1936. modal.classList.remove('hidden');
  1937. }
  1938. function openEditIPSecModal(name) {
  1939. const modal = document.getElementById('ipsec-modal');
  1940. if (!modal) return;
  1941. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1942. if (!conn) return;
  1943. const title = document.getElementById('ipsec-modal-title');
  1944. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1945. // Phase 1 Fields
  1946. safeSetVal('ipsec-modal-name', conn.name);
  1947. const nameEl = document.getElementById('ipsec-modal-name');
  1948. if (nameEl) nameEl.readOnly = true;
  1949. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1950. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1951. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1952. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1953. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1954. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1955. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1956. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1957. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1958. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1959. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1960. // Phase 2 Fields
  1961. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1962. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1963. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1964. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1965. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1966. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1967. // Populate dynamic subnets
  1968. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1969. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1970. if (localContainer) {
  1971. localContainer.innerHTML = '';
  1972. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1973. locals.forEach(s => addIpsecLocalSubnet(s));
  1974. }
  1975. if (remoteContainer) {
  1976. remoteContainer.innerHTML = '';
  1977. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1978. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1979. }
  1980. switchIpsecModalTab('p1');
  1981. modal.classList.remove('hidden');
  1982. }
  1983. function closeAddIPSecModal() {
  1984. const modal = document.getElementById('ipsec-modal');
  1985. if (modal) modal.classList.add('hidden');
  1986. }
  1987. async function submitSaveIPSec(e) {
  1988. if (e) e.preventDefault();
  1989. const name = safeGetVal('ipsec-modal-name').trim();
  1990. if (!name) {
  1991. showToast('Error', 'Tunnel name is required', 'error');
  1992. return;
  1993. }
  1994. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1995. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1996. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1997. const comments = safeGetVal('ipsec-modal-comments').trim();
  1998. const psk = safeGetVal('ipsec-modal-psk');
  1999. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2000. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2001. const localId = safeGetVal('ipsec-modal-localid').trim();
  2002. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2003. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2004. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2005. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2006. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2007. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2008. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2009. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2010. // Scrape dynamic local and remote subnets
  2011. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2012. const localSubnets = [];
  2013. localInputs.forEach(inp => {
  2014. const v = inp.value.trim();
  2015. if (v) localSubnets.push(v);
  2016. });
  2017. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2018. const remoteSubnets = [];
  2019. remoteInputs.forEach(inp => {
  2020. const v = inp.value.trim();
  2021. if (v) remoteSubnets.push(v);
  2022. });
  2023. try {
  2024. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2025. method: 'POST',
  2026. headers: { 'Content-Type': 'application/json' },
  2027. body: JSON.stringify({
  2028. name,
  2029. comment: comments,
  2030. ike_version: ikeVersion,
  2031. local_addrs: localAddrs,
  2032. remote_addrs: remotegw,
  2033. preshared_key: psk,
  2034. ike_proposals: ikeProposals,
  2035. ike_keylife: ikeKeylife,
  2036. local_id: localId,
  2037. remote_id: remoteId,
  2038. dpd: dpd,
  2039. phase2_name: phase2Name,
  2040. esp_proposals: espProposals,
  2041. esp_keylife: espKeylife,
  2042. pfs_group: pfsGroup,
  2043. pfs: pfsGroup !== 'none',
  2044. local_subnets: localSubnets,
  2045. remote_subnets: remoteSubnets,
  2046. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2047. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2048. auto_start: autostart,
  2049. disabled
  2050. })
  2051. });
  2052. if (res.ok) {
  2053. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2054. closeAddIPSecModal();
  2055. loadIPSec(false);
  2056. } else {
  2057. const err = await res.json();
  2058. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2059. }
  2060. } catch (err) {
  2061. showToast('Error', err.message, 'error');
  2062. }
  2063. }
  2064. async function startIPSecTunnel(name) {
  2065. try {
  2066. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2067. if (res.ok) {
  2068. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2069. setTimeout(() => loadIPSec(false), 2000);
  2070. }
  2071. } catch (err) {
  2072. showToast('Error', err.message, 'error');
  2073. }
  2074. }
  2075. async function stopIPSecTunnel(name) {
  2076. try {
  2077. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2078. if (res.ok) {
  2079. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2080. loadIPSec(false);
  2081. }
  2082. } catch (err) {
  2083. showToast('Error', err.message, 'error');
  2084. }
  2085. }
  2086. async function toggleIPSecState(name, enable) {
  2087. try {
  2088. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2089. method: 'POST',
  2090. headers: { 'Content-Type': 'application/json' },
  2091. body: JSON.stringify({ enabled: enable })
  2092. });
  2093. if (res.ok) {
  2094. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2095. loadIPSec(false);
  2096. }
  2097. } catch (err) {
  2098. showToast('Error', err.message, 'error');
  2099. }
  2100. }
  2101. async function deleteIPSecConn(name) {
  2102. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2103. try {
  2104. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2105. if (res.ok) {
  2106. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2107. loadIPSec(false);
  2108. fetchData(false);
  2109. }
  2110. } catch (err) {
  2111. showToast('Error', err.message, 'error');
  2112. }
  2113. }
  2114. // ======================== L2TP Multi-Instance ========================
  2115. async function loadL2TP(populateInputs = true) {
  2116. try {
  2117. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2118. await fetchPPPProfilesList();
  2119. }
  2120. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2121. const list = await res.json();
  2122. state.l2tpList = Array.isArray(list) ? list : [];
  2123. const badge = document.getElementById('l2tp-count-badge');
  2124. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2125. const tbody = document.getElementById('l2tp-table-body');
  2126. const empty = document.getElementById('l2tp-empty');
  2127. if (!tbody) return;
  2128. tbody.innerHTML = '';
  2129. if (state.l2tpList.length === 0) {
  2130. if (empty) empty.classList.remove('hidden');
  2131. } else {
  2132. if (empty) empty.classList.add('hidden');
  2133. state.l2tpList.forEach(inst => {
  2134. const tr = document.createElement('tr');
  2135. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2136. tr.innerHTML = `
  2137. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2138. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2139. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2140. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2141. <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>
  2142. <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>
  2143. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2144. <td class="py-2.5 px-3 text-center">
  2145. <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'}">
  2146. ${inst.default_route ? 'Yes' : 'No'}
  2147. </span>
  2148. </td>
  2149. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2150. ${inst.running ? `
  2151. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2152. ` : `
  2153. <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>
  2154. `}
  2155. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2156. ${inst.disabled ? 'Enable' : 'Disable'}
  2157. </button>
  2158. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2159. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2160. </td>
  2161. `;
  2162. tbody.appendChild(tr);
  2163. });
  2164. }
  2165. } catch (err) {
  2166. console.error('Failed to load L2TP:', err);
  2167. }
  2168. }
  2169. async function openAddL2TPModal() {
  2170. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2171. await fetchPPPProfilesList();
  2172. }
  2173. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2174. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2175. document.getElementById('l2tp-modal-name').readOnly = false;
  2176. document.getElementById('l2tp-modal-server').value = '';
  2177. document.getElementById('l2tp-modal-user').value = '';
  2178. document.getElementById('l2tp-modal-pass').value = '';
  2179. document.getElementById('l2tp-modal-ipsec').value = '';
  2180. document.getElementById('l2tp-modal-defroute').checked = true;
  2181. document.getElementById('l2tp-modal-disabled').checked = false;
  2182. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2183. document.getElementById('l2tp-modal').classList.remove('hidden');
  2184. }
  2185. async function openEditL2TPModal(name) {
  2186. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2187. await fetchPPPProfilesList();
  2188. }
  2189. const inst = (state.l2tpList || []).find(i => i.name === name);
  2190. if (!inst) return;
  2191. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2192. document.getElementById('l2tp-modal-name').value = inst.name;
  2193. document.getElementById('l2tp-modal-name').readOnly = true;
  2194. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2195. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2196. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2197. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2198. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2199. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2200. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2201. document.getElementById('l2tp-modal').classList.remove('hidden');
  2202. }
  2203. function closeL2TPModal() {
  2204. document.getElementById('l2tp-modal').classList.add('hidden');
  2205. }
  2206. async function submitSaveL2TP(e) {
  2207. e.preventDefault();
  2208. const name = document.getElementById('l2tp-modal-name').value.trim();
  2209. const server = document.getElementById('l2tp-modal-server').value.trim();
  2210. const user = document.getElementById('l2tp-modal-user').value.trim();
  2211. const pass = document.getElementById('l2tp-modal-pass').value;
  2212. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2213. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2214. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2215. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2216. try {
  2217. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2218. method: 'POST',
  2219. headers: { 'Content-Type': 'application/json' },
  2220. body: JSON.stringify({
  2221. name,
  2222. connect_to: server,
  2223. username: user,
  2224. password: pass,
  2225. profile: profile,
  2226. ipsec_secret: ipsec,
  2227. default_route: defRoute,
  2228. disabled
  2229. })
  2230. });
  2231. if (res.ok) {
  2232. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2233. closeL2TPModal();
  2234. loadL2TP(false);
  2235. fetchData(false);
  2236. }
  2237. } catch (err) {
  2238. showToast('Error', err.message, 'error');
  2239. }
  2240. }
  2241. async function connectL2TPInstance(name) {
  2242. try {
  2243. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2244. if (res.ok) {
  2245. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2246. setTimeout(() => loadL2TP(false), 2000);
  2247. }
  2248. } catch (err) {
  2249. showToast('Error', err.message, 'error');
  2250. }
  2251. }
  2252. async function disconnectL2TPInstance(name) {
  2253. try {
  2254. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2255. if (res.ok) {
  2256. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2257. loadL2TP(false);
  2258. }
  2259. } catch (err) {
  2260. showToast('Error', err.message, 'error');
  2261. }
  2262. }
  2263. async function toggleL2TPState(name, enable) {
  2264. try {
  2265. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2266. method: 'POST',
  2267. headers: { 'Content-Type': 'application/json' },
  2268. body: JSON.stringify({ enabled: enable })
  2269. });
  2270. if (res.ok) {
  2271. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2272. loadL2TP(false);
  2273. }
  2274. } catch (err) {
  2275. showToast('Error', err.message, 'error');
  2276. }
  2277. }
  2278. async function deleteL2TPInstance(name) {
  2279. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2280. try {
  2281. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2282. if (res.ok) {
  2283. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2284. loadL2TP(false);
  2285. fetchData(false);
  2286. }
  2287. } catch (err) {
  2288. showToast('Error', err.message, 'error');
  2289. }
  2290. }
  2291. // ======================== PPTP Multi-Instance ========================
  2292. async function loadPPTP(populateInputs = true) {
  2293. try {
  2294. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2295. await fetchPPPProfilesList();
  2296. }
  2297. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2298. const list = await res.json();
  2299. state.pptpList = Array.isArray(list) ? list : [];
  2300. const badge = document.getElementById('pptp-count-badge');
  2301. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2302. const tbody = document.getElementById('pptp-table-body');
  2303. const empty = document.getElementById('pptp-empty');
  2304. if (!tbody) return;
  2305. tbody.innerHTML = '';
  2306. if (state.pptpList.length === 0) {
  2307. if (empty) empty.classList.remove('hidden');
  2308. } else {
  2309. if (empty) empty.classList.add('hidden');
  2310. state.pptpList.forEach(inst => {
  2311. const tr = document.createElement('tr');
  2312. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2313. tr.innerHTML = `
  2314. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2315. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2316. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2317. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2318. <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>
  2319. <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>
  2320. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2321. <td class="py-2.5 px-3 text-center">
  2322. <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'}">
  2323. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2324. </span>
  2325. </td>
  2326. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2327. ${inst.running ? `
  2328. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2329. ` : `
  2330. <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>
  2331. `}
  2332. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2333. ${inst.disabled ? 'Enable' : 'Disable'}
  2334. </button>
  2335. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2336. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2337. </td>
  2338. `;
  2339. tbody.appendChild(tr);
  2340. });
  2341. }
  2342. } catch (err) {
  2343. console.error('Failed to load PPTP:', err);
  2344. }
  2345. }
  2346. async function openAddPPTPModal() {
  2347. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2348. await fetchPPPProfilesList();
  2349. }
  2350. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2351. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2352. document.getElementById('pptp-modal-name').readOnly = false;
  2353. document.getElementById('pptp-modal-server').value = '';
  2354. document.getElementById('pptp-modal-user').value = '';
  2355. document.getElementById('pptp-modal-pass').value = '';
  2356. document.getElementById('pptp-modal-mppe').checked = true;
  2357. document.getElementById('pptp-modal-defroute').checked = true;
  2358. document.getElementById('pptp-modal-disabled').checked = false;
  2359. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2360. document.getElementById('pptp-modal').classList.remove('hidden');
  2361. }
  2362. async function openEditPPTPModal(name) {
  2363. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2364. await fetchPPPProfilesList();
  2365. }
  2366. const inst = (state.pptpList || []).find(i => i.name === name);
  2367. if (!inst) return;
  2368. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2369. document.getElementById('pptp-modal-name').value = inst.name;
  2370. document.getElementById('pptp-modal-name').readOnly = true;
  2371. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2372. document.getElementById('pptp-modal-user').value = inst.username || '';
  2373. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2374. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2375. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2376. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2377. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2378. document.getElementById('pptp-modal').classList.remove('hidden');
  2379. }
  2380. function closePPTPModal() {
  2381. document.getElementById('pptp-modal').classList.add('hidden');
  2382. }
  2383. async function submitSavePPTP(e) {
  2384. e.preventDefault();
  2385. const name = document.getElementById('pptp-modal-name').value.trim();
  2386. const server = document.getElementById('pptp-modal-server').value.trim();
  2387. const user = document.getElementById('pptp-modal-user').value.trim();
  2388. const pass = document.getElementById('pptp-modal-pass').value;
  2389. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2390. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2391. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2392. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2393. try {
  2394. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2395. method: 'POST',
  2396. headers: { 'Content-Type': 'application/json' },
  2397. body: JSON.stringify({
  2398. name,
  2399. connect_to: server,
  2400. username: user,
  2401. password: pass,
  2402. profile: profile,
  2403. require_mppe: mppe,
  2404. default_route: defRoute,
  2405. auto_reconnect: true,
  2406. disabled
  2407. })
  2408. });
  2409. if (res.ok) {
  2410. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2411. closePPTPModal();
  2412. loadPPTP(false);
  2413. fetchData(false);
  2414. }
  2415. } catch (err) {
  2416. showToast('Error', err.message, 'error');
  2417. }
  2418. }
  2419. async function connectPPTPInstance(name) {
  2420. try {
  2421. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2422. if (res.ok) {
  2423. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2424. setTimeout(() => loadPPTP(false), 2000);
  2425. }
  2426. } catch (err) {
  2427. showToast('Error', err.message, 'error');
  2428. }
  2429. }
  2430. async function disconnectPPTPInstance(name) {
  2431. try {
  2432. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2433. if (res.ok) {
  2434. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2435. loadPPTP(false);
  2436. }
  2437. } catch (err) {
  2438. showToast('Error', err.message, 'error');
  2439. }
  2440. }
  2441. async function togglePPTPState(name, enable) {
  2442. try {
  2443. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2444. method: 'POST',
  2445. headers: { 'Content-Type': 'application/json' },
  2446. body: JSON.stringify({ enabled: enable })
  2447. });
  2448. if (res.ok) {
  2449. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2450. loadPPTP(false);
  2451. }
  2452. } catch (err) {
  2453. showToast('Error', err.message, 'error');
  2454. }
  2455. }
  2456. async function deletePPTPInstance(name) {
  2457. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2458. try {
  2459. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2460. if (res.ok) {
  2461. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2462. loadPPTP(false);
  2463. fetchData(false);
  2464. }
  2465. } catch (err) {
  2466. showToast('Error', err.message, 'error');
  2467. }
  2468. }
  2469. // ---------------- Modal & Helper Functions ----------------
  2470. function openVlanModal(defaultParent = '') {
  2471. const select = document.getElementById('vlan-parent');
  2472. select.innerHTML = '';
  2473. const allIfaces = state.interfaces || [];
  2474. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2475. if (eligible.length === 0) {
  2476. const opt = document.createElement('option');
  2477. opt.value = '';
  2478. opt.innerText = 'No VLAN-capable interfaces available';
  2479. select.appendChild(opt);
  2480. } else {
  2481. eligible.forEach(i => {
  2482. const opt = document.createElement('option');
  2483. opt.value = i.name;
  2484. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2485. if (i.name === defaultParent) opt.selected = true;
  2486. select.appendChild(opt);
  2487. });
  2488. }
  2489. document.getElementById('vlan-id').value = '';
  2490. document.getElementById('vlan-name').value = '';
  2491. document.getElementById('vlan-ip').value = '';
  2492. document.getElementById('vlan-desc').value = '';
  2493. autoSuggestVlanName();
  2494. document.getElementById('vlan-modal').classList.remove('hidden');
  2495. }
  2496. function closeVlanModal() {
  2497. document.getElementById('vlan-modal').classList.add('hidden');
  2498. }
  2499. function autoSuggestVlanName() {
  2500. const parent = document.getElementById('vlan-parent').value;
  2501. if (!parent) return;
  2502. const id = document.getElementById('vlan-id').value;
  2503. const nameInput = document.getElementById('vlan-name');
  2504. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2505. }
  2506. function setSubnetPreset(cidr) {
  2507. const ipInput = document.getElementById('vlan-ip');
  2508. const id = document.getElementById('vlan-id').value || '10';
  2509. ipInput.value = `192.168.${id}.1${cidr}`;
  2510. }
  2511. async function submitCreateVlan(e) {
  2512. e.preventDefault();
  2513. const btn = document.getElementById('vlan-submit-btn');
  2514. btn.disabled = true;
  2515. btn.innerText = 'Creating...';
  2516. const parent = document.getElementById('vlan-parent').value;
  2517. if (!parent) {
  2518. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2519. btn.disabled = false;
  2520. btn.innerText = 'Create VLAN';
  2521. return;
  2522. }
  2523. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2524. const name = document.getElementById('vlan-name').value.trim();
  2525. const ip = document.getElementById('vlan-ip').value.trim();
  2526. const role = document.getElementById('vlan-role').value;
  2527. const desc = document.getElementById('vlan-desc').value.trim();
  2528. try {
  2529. const res = await fetch(`${API_BASE}/vlans`, {
  2530. method: 'POST',
  2531. headers: { 'Content-Type': 'application/json' },
  2532. body: JSON.stringify({
  2533. parent_name: parent,
  2534. vlan_id: id,
  2535. name: name,
  2536. ip_address: ip,
  2537. role: role,
  2538. description: desc,
  2539. mtu: 1500,
  2540. auto_up: true
  2541. })
  2542. });
  2543. const data = await res.json();
  2544. if (res.ok) {
  2545. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2546. state.expandedParents.add(parent);
  2547. closeVlanModal();
  2548. await fetchData(true);
  2549. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2550. } else {
  2551. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2552. }
  2553. } catch (err) {
  2554. showToast('Error', err.message, 'error');
  2555. } finally {
  2556. btn.disabled = false;
  2557. btn.innerText = 'Create VLAN';
  2558. }
  2559. }
  2560. async function confirmDeleteVlan(name) {
  2561. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2562. try {
  2563. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2564. if (res.ok) {
  2565. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2566. closeIfaceModal();
  2567. fetchData(true);
  2568. }
  2569. } catch (err) {
  2570. showToast('Error', err.message, 'error');
  2571. }
  2572. }
  2573. function openIfaceModal(name) {
  2574. const iface = (state.interfaces || []).find(i => i.name === name);
  2575. if (!iface) return;
  2576. state.currentModalIface = iface.name;
  2577. document.getElementById('modal-iface-name').innerText = iface.name;
  2578. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2579. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2580. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2581. document.getElementById('modal-iface-desc').value = iface.description || '';
  2582. const nameInput = document.getElementById('modal-iface-new-name');
  2583. const renameBtn = document.getElementById('modal-btn-rename');
  2584. const renameHelp = document.getElementById('modal-iface-rename-help');
  2585. if (nameInput) {
  2586. nameInput.value = iface.name;
  2587. if (iface.name === 'lo' || iface.type === 'loopback') {
  2588. nameInput.disabled = true;
  2589. if (renameBtn) renameBtn.disabled = true;
  2590. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  2591. } else {
  2592. nameInput.disabled = false;
  2593. if (renameBtn) renameBtn.disabled = false;
  2594. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  2595. }
  2596. }
  2597. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2598. if (iface.is_vlan) {
  2599. delBtn.classList.remove('hidden');
  2600. } else {
  2601. delBtn.classList.add('hidden');
  2602. }
  2603. renderModalIPs(iface);
  2604. document.getElementById('iface-modal').classList.remove('hidden');
  2605. }
  2606. function renderModalIPs(iface) {
  2607. const container = document.getElementById('modal-ip-list');
  2608. container.innerHTML = '';
  2609. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2610. if (addrs.length === 0) {
  2611. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2612. return;
  2613. }
  2614. addrs.forEach(addr => {
  2615. const row = document.createElement('div');
  2616. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2617. row.innerHTML = `
  2618. <span class="text-white">${addr}</span>
  2619. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2620. `;
  2621. container.appendChild(row);
  2622. });
  2623. }
  2624. function closeIfaceModal() {
  2625. document.getElementById('iface-modal').classList.add('hidden');
  2626. state.currentModalIface = null;
  2627. }
  2628. async function setIfaceState(name, newState) {
  2629. const target = name || state.currentModalIface;
  2630. if (!target) return;
  2631. await toggleInterfaceState(target, newState);
  2632. const updated = (state.interfaces || []).find(i => i.name === target);
  2633. if (updated) openIfaceModal(target);
  2634. }
  2635. async function applyMTU() {
  2636. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2637. try {
  2638. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2639. method: 'POST',
  2640. headers: { 'Content-Type': 'application/json' },
  2641. body: JSON.stringify({ mtu })
  2642. });
  2643. if (res.ok) {
  2644. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2645. fetchData(false);
  2646. }
  2647. } catch (err) {
  2648. showToast('Error', err.message, 'error');
  2649. }
  2650. }
  2651. async function addInterfaceIP() {
  2652. const ip = document.getElementById('modal-new-ip').value.trim();
  2653. if (!ip) return;
  2654. try {
  2655. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2656. method: 'POST',
  2657. headers: { 'Content-Type': 'application/json' },
  2658. body: JSON.stringify({ ip })
  2659. });
  2660. if (res.ok) {
  2661. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2662. document.getElementById('modal-new-ip').value = '';
  2663. await fetchData(false);
  2664. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2665. if (iface) renderModalIPs(iface);
  2666. } else {
  2667. const err = await res.json();
  2668. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2669. }
  2670. } catch (err) {
  2671. showToast('Error', err.message, 'error');
  2672. }
  2673. }
  2674. async function removeInterfaceIP(ip) {
  2675. if (!confirm(`Remove IP ${ip}?`)) return;
  2676. try {
  2677. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2678. method: 'DELETE',
  2679. headers: { 'Content-Type': 'application/json' },
  2680. body: JSON.stringify({ ip })
  2681. });
  2682. if (res.ok) {
  2683. showToast('IP Removed', `Removed ${ip}`, 'success');
  2684. await fetchData(false);
  2685. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2686. if (iface) renderModalIPs(iface);
  2687. }
  2688. } catch (err) {
  2689. showToast('Error', err.message, 'error');
  2690. }
  2691. }
  2692. async function renameInterface() {
  2693. const oldName = state.currentModalIface;
  2694. const newNameInput = document.getElementById('modal-iface-new-name');
  2695. const newName = (newNameInput?.value || '').trim();
  2696. if (!oldName) return;
  2697. if (!newName) {
  2698. showToast('Warning', 'Interface name cannot be empty', 'warning');
  2699. return;
  2700. }
  2701. if (newName === oldName) {
  2702. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  2703. return;
  2704. }
  2705. if (newName.length > 15) {
  2706. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  2707. return;
  2708. }
  2709. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  2710. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  2711. return;
  2712. }
  2713. const renameBtn = document.getElementById('modal-btn-rename');
  2714. if (renameBtn) {
  2715. renameBtn.disabled = true;
  2716. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  2717. }
  2718. try {
  2719. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2720. method: 'POST',
  2721. headers: { 'Content-Type': 'application/json' },
  2722. body: JSON.stringify({ new_name: newName })
  2723. });
  2724. const data = await res.json();
  2725. if (!res.ok) {
  2726. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  2727. return;
  2728. }
  2729. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  2730. state.currentModalIface = newName;
  2731. document.getElementById('modal-iface-name').innerText = newName;
  2732. // Refresh application state
  2733. await fetchData(false);
  2734. const updated = (state.interfaces || []).find(i => i.name === newName);
  2735. if (updated) {
  2736. openIfaceModal(newName);
  2737. } else {
  2738. closeIfaceModal();
  2739. }
  2740. } catch (err) {
  2741. showToast('Error', err.message, 'error');
  2742. } finally {
  2743. if (renameBtn) {
  2744. renameBtn.disabled = false;
  2745. renameBtn.innerHTML = `
  2746. <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>
  2747. <span>Rename</span>
  2748. `;
  2749. }
  2750. }
  2751. }
  2752. async function saveInterfaceMetadata() {
  2753. const oldName = state.currentModalIface;
  2754. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  2755. const role = document.getElementById('modal-iface-role').value;
  2756. const desc = document.getElementById('modal-iface-desc').value.trim();
  2757. let targetName = oldName;
  2758. // If user changed the name before clicking Save Changes, execute rename first
  2759. if (newName && newName !== oldName && oldName !== 'lo') {
  2760. try {
  2761. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2762. method: 'POST',
  2763. headers: { 'Content-Type': 'application/json' },
  2764. body: JSON.stringify({ new_name: newName })
  2765. });
  2766. const data = await renameRes.json();
  2767. if (!renameRes.ok) {
  2768. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  2769. return;
  2770. }
  2771. targetName = newName;
  2772. state.currentModalIface = newName;
  2773. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  2774. } catch (err) {
  2775. showToast('Error', err.message, 'error');
  2776. return;
  2777. }
  2778. }
  2779. try {
  2780. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  2781. method: 'POST',
  2782. headers: { 'Content-Type': 'application/json' },
  2783. body: JSON.stringify({ role, description: desc })
  2784. });
  2785. if (res.ok) {
  2786. showToast('Saved', 'Interface configuration updated', 'success');
  2787. closeIfaceModal();
  2788. fetchData(false);
  2789. } else {
  2790. const err = await res.json();
  2791. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  2792. }
  2793. } catch (err) {
  2794. showToast('Error', err.message, 'error');
  2795. }
  2796. }
  2797. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2798. state.fwSubTab = 'filter';
  2799. state.routesSubTab = 'routes';
  2800. function renderRuleFlag(disabled, hasComment) {
  2801. let flags = '';
  2802. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2803. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2804. return flags || '<span class="text-slate-600">-</span>';
  2805. }
  2806. function renderActionBadge(action) {
  2807. const act = (action || '').toLowerCase();
  2808. let color = 'bg-slate-800 text-slate-300';
  2809. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2810. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2811. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2812. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2813. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2814. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2815. }
  2816. function switchFWSubTab(tab) {
  2817. state.fwSubTab = tab;
  2818. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2819. tabs.forEach(t => {
  2820. const panel = document.getElementById(`fw-subtab-${t}`);
  2821. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2822. if (panel) {
  2823. if (t === tab) panel.classList.remove('hidden');
  2824. else panel.classList.add('hidden');
  2825. }
  2826. if (btn) {
  2827. if (t === tab) {
  2828. 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';
  2829. } else {
  2830. 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';
  2831. }
  2832. }
  2833. });
  2834. const addBtn = document.getElementById('fw-primary-add-btn');
  2835. if (addBtn) {
  2836. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2837. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2838. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2839. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2840. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2841. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2842. }
  2843. if (tab === 'geo') loadGeoIP();
  2844. if (tab === 'connections') loadConnections();
  2845. setTimeout(initTableSorting, 50);
  2846. }
  2847. function openCurrentFWModal() {
  2848. if (state.fwSubTab === 'filter') openAddFilterModal();
  2849. else if (state.fwSubTab === 'nat') openAddNATModal();
  2850. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2851. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2852. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2853. else if (state.fwSubTab === 'connections') loadConnections();
  2854. }
  2855. async function loadFirewall(populateDropdowns = true) {
  2856. try {
  2857. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2858. fetch(`${API_BASE}/firewall/summary`),
  2859. fetch(`${API_BASE}/firewall/filter`),
  2860. fetch(`${API_BASE}/firewall/nat`),
  2861. fetch(`${API_BASE}/firewall/mangle`),
  2862. fetch(`${API_BASE}/firewall/address-lists`),
  2863. fetch(`${API_BASE}/firewall/geoip/status`),
  2864. fetch(`${API_BASE}/firewall/geoip/countries`)
  2865. ]);
  2866. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2867. if (filterRes.ok) state.filterRules = await filterRes.json();
  2868. if (natRes.ok) state.natRules = await natRes.json();
  2869. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2870. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2871. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2872. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2873. // Badges
  2874. const bFilter = document.getElementById('fw-badge-filter');
  2875. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2876. const bNat = document.getElementById('fw-badge-nat');
  2877. if (bNat) bNat.innerText = (state.natRules || []).length;
  2878. const bMangle = document.getElementById('fw-badge-mangle');
  2879. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2880. const bAddr = document.getElementById('fw-badge-addrlist');
  2881. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2882. const bGeo = document.getElementById('fw-badge-geo');
  2883. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2884. renderFilterRules();
  2885. renderNATRules();
  2886. renderMangleRules();
  2887. renderAddressLists();
  2888. renderGeoCountries();
  2889. if (state.fwSubTab === 'connections') {
  2890. loadConnections();
  2891. }
  2892. } catch (err) {
  2893. console.error('Failed to load firewall:', err);
  2894. }
  2895. }
  2896. // ----------------- Filter Rules -----------------
  2897. function renderFilterRules() {
  2898. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2899. const tbody = document.getElementById('filter-table-body');
  2900. const empty = document.getElementById('filter-empty');
  2901. if (!tbody) return;
  2902. tbody.innerHTML = '';
  2903. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2904. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2905. if (rules.length === 0) {
  2906. empty?.classList.remove('hidden');
  2907. return;
  2908. }
  2909. empty?.classList.add('hidden');
  2910. rules.forEach((r, idx) => {
  2911. const tr = document.createElement('tr');
  2912. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2913. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2914. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2915. let actionExtra = '';
  2916. if (r.action === 'reject') {
  2917. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2918. } else if (r.action === 'jump') {
  2919. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2920. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2921. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2922. } else if (r.action === 'log' && r.log_prefix) {
  2923. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2924. }
  2925. tr.innerHTML = `
  2926. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2927. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2928. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2929. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2930. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2931. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2932. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2933. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2934. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2935. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2936. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2937. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2938. </td>
  2939. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2940. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2941. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2942. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2943. <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>
  2944. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2945. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2946. </td>
  2947. `;
  2948. tbody.appendChild(tr);
  2949. });
  2950. }
  2951. function formatTarget(addr, list, geo) {
  2952. const parts = [];
  2953. if (addr) parts.push(`<span>${addr}</span>`);
  2954. if (list) {
  2955. const inv = list.startsWith('!') ? '!' : '';
  2956. const clean = list.replace(/^!/, '');
  2957. 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>`);
  2958. }
  2959. if (geo) {
  2960. const inv = geo.startsWith('!') ? '!' : '';
  2961. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2962. 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>`);
  2963. }
  2964. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2965. return parts.join(' ');
  2966. }
  2967. function populateInterfaceSelect(selectId, currentVal = '') {
  2968. const sel = document.getElementById(selectId);
  2969. if (!sel) return;
  2970. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2971. (state.interfaces || []).forEach(i => {
  2972. const opt = document.createElement('option');
  2973. opt.value = i.name;
  2974. opt.innerText = `${i.name} (${i.role || i.type})`;
  2975. if (i.name === currentVal) opt.selected = true;
  2976. sel.appendChild(opt);
  2977. });
  2978. }
  2979. function populateAddressListSelect(selectId, currentVal = '') {
  2980. const sel = document.getElementById(selectId);
  2981. if (!sel) return;
  2982. sel.innerHTML = '<option value="">(None)</option>';
  2983. const cleanVal = (currentVal || '').replace(/^!/, '');
  2984. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2985. customNames.forEach(name => {
  2986. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2987. const opt = document.createElement('option');
  2988. opt.value = name;
  2989. opt.innerText = `${name} (${count} entries)`;
  2990. if (name === cleanVal) opt.selected = true;
  2991. sel.appendChild(opt);
  2992. });
  2993. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2994. const opt = document.createElement('option');
  2995. opt.value = cleanVal;
  2996. opt.innerText = cleanVal;
  2997. opt.selected = true;
  2998. sel.appendChild(opt);
  2999. }
  3000. populateCommonAddrListDatalist();
  3001. }
  3002. function populateCommonAddrListDatalist() {
  3003. const dl = document.getElementById('fw-addrlist-datalist');
  3004. if (!dl) return;
  3005. dl.innerHTML = '';
  3006. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3007. names.forEach(name => {
  3008. const opt = document.createElement('option');
  3009. opt.value = name;
  3010. dl.appendChild(opt);
  3011. });
  3012. }
  3013. function populateGeoIPSelect(selectId, currentVal = '') {
  3014. const sel = document.getElementById(selectId);
  3015. if (!sel) return;
  3016. sel.innerHTML = '<option value="">(None)</option>';
  3017. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3018. // Presets optgroup
  3019. const grpPresets = document.createElement('optgroup');
  3020. grpPresets.label = '⚡ Regional Presets';
  3021. const presets = [
  3022. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3023. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3024. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3025. ];
  3026. presets.forEach(p => {
  3027. const opt = document.createElement('option');
  3028. opt.value = p.code;
  3029. opt.innerText = p.label;
  3030. if (p.code === cleanVal) opt.selected = true;
  3031. grpPresets.appendChild(opt);
  3032. });
  3033. sel.appendChild(grpPresets);
  3034. // All Countries optgroup
  3035. const grpCountries = document.createElement('optgroup');
  3036. grpCountries.label = '🌍 All Countries';
  3037. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3038. countries.forEach(c => {
  3039. const opt = document.createElement('option');
  3040. opt.value = c.code;
  3041. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3042. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3043. if (c.code === cleanVal) opt.selected = true;
  3044. grpCountries.appendChild(opt);
  3045. });
  3046. sel.appendChild(grpCountries);
  3047. }
  3048. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3049. function switchFwRuleTab(tab) {
  3050. state.activeFwRuleTab = tab;
  3051. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3052. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3053. btn.classList.add('text-slate-400', 'border-transparent');
  3054. });
  3055. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3056. if (activeBtn) {
  3057. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3058. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3059. }
  3060. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3061. const activePane = document.getElementById(`fw-pane-${tab}`);
  3062. if (activePane) activePane.classList.remove('hidden');
  3063. if (tab === 'statistics') {
  3064. startFwStatPolling();
  3065. } else {
  3066. stopFwStatPolling();
  3067. }
  3068. }
  3069. function toggleFwField(fieldKey, expand) {
  3070. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3071. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3072. if (!plusBtn || !fieldBox) return;
  3073. if (expand) {
  3074. plusBtn.classList.add('hidden');
  3075. fieldBox.classList.remove('hidden');
  3076. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3077. if (valInput) valInput.focus();
  3078. } else {
  3079. fieldBox.classList.add('hidden');
  3080. plusBtn.classList.remove('hidden');
  3081. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3082. if (valInput) {
  3083. if (valInput.tagName === 'SELECT') {
  3084. valInput.selectedIndex = 0;
  3085. } else {
  3086. valInput.value = '';
  3087. }
  3088. }
  3089. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3090. if (invInput) invInput.checked = false;
  3091. if (fieldKey === 'cs') {
  3092. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3093. const el = document.getElementById(id);
  3094. if (el) el.checked = false;
  3095. });
  3096. }
  3097. if (fieldKey === 'natstate') {
  3098. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3099. const el = document.getElementById(id);
  3100. if (el) el.checked = false;
  3101. });
  3102. }
  3103. if (fieldKey === 'days') {
  3104. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3105. const el = document.getElementById(`fw-day-${d}`);
  3106. if (el) el.checked = true;
  3107. });
  3108. }
  3109. }
  3110. }
  3111. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3112. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3113. toggleFwField(fieldKey, true);
  3114. let strVal = String(value);
  3115. if (hasInvert) {
  3116. const inv = strVal.startsWith('!');
  3117. if (inv) strVal = strVal.slice(1);
  3118. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3119. if (invEl) invEl.checked = inv;
  3120. }
  3121. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3122. if (valEl) valEl.value = strVal;
  3123. } else {
  3124. toggleFwField(fieldKey, false);
  3125. }
  3126. }
  3127. function getFwFieldVal(fieldKey, hasInvert = false) {
  3128. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3129. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3130. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3131. let v = valEl ? valEl.value.trim() : '';
  3132. if (!v) return '';
  3133. if (hasInvert) {
  3134. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3135. if (invEl && invEl.checked) {
  3136. v = '!' + v.replace(/^!/, '');
  3137. }
  3138. }
  3139. return v;
  3140. }
  3141. function toggleMaximizeFilterModal() {
  3142. const win = document.getElementById('filter-modal-window');
  3143. if (!win) return;
  3144. if (win.classList.contains('max-w-[720px]')) {
  3145. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3146. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3147. } else {
  3148. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3149. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3150. }
  3151. }
  3152. function openAddFilterModal() {
  3153. switchFwRuleTab('general');
  3154. const badge = document.getElementById('fw-modal-badge');
  3155. if (badge) badge.innerText = 'New...';
  3156. document.getElementById('filter-modal-id').value = '';
  3157. document.getElementById('filter-modal-enabled').checked = true;
  3158. document.getElementById('filter-modal-comment').value = '';
  3159. document.getElementById('filter-modal-chain').value = 'forward';
  3160. document.getElementById('filter-modal-action').value = 'accept';
  3161. document.getElementById('filter-modal-log').checked = false;
  3162. populateInterfaceSelect('fw-val-iniface');
  3163. populateInterfaceSelect('fw-val-outiface');
  3164. populateAddressListSelect('fw-val-srclist');
  3165. populateAddressListSelect('fw-val-dstlist');
  3166. populateGeoIPSelect('fw-val-srcgeo');
  3167. populateGeoIPSelect('fw-val-dstgeo');
  3168. const allFieldKeys = [
  3169. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3170. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3171. 'routingmark', 'conntype', 'cs', 'natstate',
  3172. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3173. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3174. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3175. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3176. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3177. ];
  3178. allFieldKeys.forEach(k => toggleFwField(k, false));
  3179. resetCurrentRuleCounters();
  3180. toggleFilterActionFields();
  3181. document.getElementById('filter-modal').classList.remove('hidden');
  3182. }
  3183. function openEditFilterModal(id) {
  3184. const r = (state.filterRules || []).find(rule => rule.id === id);
  3185. if (!r) return;
  3186. switchFwRuleTab('general');
  3187. const badge = document.getElementById('fw-modal-badge');
  3188. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3189. document.getElementById('filter-modal-id').value = r.id;
  3190. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3191. document.getElementById('filter-modal-comment').value = r.comment || '';
  3192. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3193. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3194. document.getElementById('filter-modal-log').checked = !!r.log;
  3195. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3196. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3197. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3198. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3199. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3200. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3201. setFwFieldVal('src', r.src_address, true);
  3202. setFwFieldVal('dst', r.dst_address, true);
  3203. setFwFieldVal('srclist', r.src_address_list, true);
  3204. setFwFieldVal('dstlist', r.dst_address_list, true);
  3205. setFwFieldVal('srcgeo', r.src_geoip, true);
  3206. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3207. if (r.protocol && r.protocol !== 'all') {
  3208. setFwFieldVal('proto', r.protocol, true);
  3209. } else {
  3210. toggleFwField('proto', false);
  3211. }
  3212. setFwFieldVal('sport', r.src_port, true);
  3213. setFwFieldVal('dport', r.dst_port, true);
  3214. setFwFieldVal('anyport', r.any_port, true);
  3215. setFwFieldVal('iniface', r.in_interface, true);
  3216. setFwFieldVal('outiface', r.out_interface, true);
  3217. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3218. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3219. setFwFieldVal('pktmark', r.packet_mark, true);
  3220. setFwFieldVal('connmark', r.connection_mark, true);
  3221. setFwFieldVal('routingmark', r.routing_mark, true);
  3222. setFwFieldVal('conntype', r.connection_type, false);
  3223. const states = r.connection_state || [];
  3224. if (states.length > 0) {
  3225. toggleFwField('cs', true);
  3226. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3227. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3228. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3229. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3230. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3231. } else {
  3232. toggleFwField('cs', false);
  3233. }
  3234. const natStates = r.connection_nat_state || [];
  3235. if (natStates.length > 0) {
  3236. toggleFwField('natstate', true);
  3237. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3238. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3239. } else {
  3240. toggleFwField('natstate', false);
  3241. }
  3242. // Advanced tab fields
  3243. setFwFieldVal('layer7', r.layer7_protocol, false);
  3244. setFwFieldVal('content', r.content, false);
  3245. setFwFieldVal('connbytes', r.connection_bytes, false);
  3246. setFwFieldVal('connrate', r.connection_rate, false);
  3247. setFwFieldVal('pcc', r.pcc, false);
  3248. setFwFieldVal('srcmac', r.src_mac_address, true);
  3249. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3250. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3251. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3252. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3253. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3254. setFwFieldVal('tlshost', r.tls_host, false);
  3255. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3256. setFwFieldVal('priority', r.priority, false);
  3257. setFwFieldVal('dscp', r.dscp, false);
  3258. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3259. if (r.tos) {
  3260. const tosEl = document.getElementById('fw-val-tos');
  3261. if (tosEl) tosEl.value = r.tos;
  3262. }
  3263. setFwFieldVal('pktsize', r.packet_size, false);
  3264. setFwFieldVal('random', r.random, false);
  3265. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3266. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3267. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3268. setFwFieldVal('ttl', r.ttl, false);
  3269. // Extra tab fields
  3270. setFwFieldVal('time', r.time, false);
  3271. if (r.days) {
  3272. toggleFwField('days', true);
  3273. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3274. const chk = document.getElementById(`fw-day-${d}`);
  3275. if (chk) chk.checked = r.days.includes(d);
  3276. });
  3277. } else {
  3278. toggleFwField('days', false);
  3279. }
  3280. setFwFieldVal('limit', r.limit, false);
  3281. setFwFieldVal('dstlimit', r.dst_limit, false);
  3282. setFwFieldVal('psd', r.psd, false);
  3283. // Action fields
  3284. if (r.reject_with) {
  3285. const rwEl = document.getElementById('filter-modal-rejectwith');
  3286. if (rwEl) rwEl.value = r.reject_with;
  3287. }
  3288. if (r.jump_target) {
  3289. const jtEl = document.getElementById('filter-modal-jumptarget');
  3290. if (jtEl) jtEl.value = r.jump_target;
  3291. }
  3292. if (r.address_list) {
  3293. const alEl = document.getElementById('filter-modal-action-addrlist');
  3294. if (alEl) alEl.value = r.address_list;
  3295. }
  3296. if (r.address_list_timeout) {
  3297. const toEl = document.getElementById('filter-modal-action-timeout');
  3298. if (toEl) toEl.value = r.address_list_timeout;
  3299. }
  3300. setFwFieldVal('logprefix', r.log_prefix, false);
  3301. // Statistics
  3302. const bEl = document.getElementById('fw-stat-bytes');
  3303. const pEl = document.getElementById('fw-stat-packets');
  3304. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3305. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3306. state.fwLastBytes = r.bytes || 0;
  3307. state.fwLastPackets = r.packets || 0;
  3308. state.fwLastTimestamp = Date.now();
  3309. state.fwStatRateHistory = new Array(30).fill(0);
  3310. state.fwStatPktHistory = new Array(30).fill(0);
  3311. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3312. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3313. toggleFilterActionFields();
  3314. document.getElementById('filter-modal').classList.remove('hidden');
  3315. }
  3316. function closeFilterModal() {
  3317. stopFwStatPolling();
  3318. document.getElementById('filter-modal').classList.add('hidden');
  3319. }
  3320. function toggleFilterActionFields() {
  3321. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3322. const rejectBox = document.getElementById('filter-action-reject-box');
  3323. const jumpBox = document.getElementById('filter-action-jump-box');
  3324. const addrBox = document.getElementById('filter-action-addrlist-box');
  3325. if (rejectBox) {
  3326. if (act === 'reject') rejectBox.classList.remove('hidden');
  3327. else rejectBox.classList.add('hidden');
  3328. }
  3329. if (jumpBox) {
  3330. if (act === 'jump') jumpBox.classList.remove('hidden');
  3331. else jumpBox.classList.add('hidden');
  3332. }
  3333. if (addrBox) {
  3334. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3335. addrBox.classList.remove('hidden');
  3336. } else {
  3337. addrBox.classList.add('hidden');
  3338. }
  3339. }
  3340. if (act === 'log') {
  3341. const logEl = document.getElementById('filter-modal-log');
  3342. if (logEl) logEl.checked = true;
  3343. toggleFwField('logprefix', true);
  3344. }
  3345. }
  3346. function toggleFwLogPrefix() {
  3347. const isLog = document.getElementById('filter-modal-log')?.checked;
  3348. toggleFwField('logprefix', !!isLog);
  3349. }
  3350. function copyFilterRule() {
  3351. document.getElementById('filter-modal-id').value = '';
  3352. const badge = document.getElementById('fw-modal-badge');
  3353. if (badge) badge.innerText = 'New...';
  3354. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3355. }
  3356. function resetCurrentRuleCounters() {
  3357. state.fwStatRateHistory = new Array(30).fill(0);
  3358. state.fwStatPktHistory = new Array(30).fill(0);
  3359. state.fwLastBytes = 0;
  3360. state.fwLastPackets = 0;
  3361. state.fwLastTimestamp = Date.now();
  3362. const bEl = document.getElementById('fw-stat-bytes');
  3363. const pEl = document.getElementById('fw-stat-packets');
  3364. const rEl = document.getElementById('fw-stat-rate');
  3365. const prEl = document.getElementById('fw-stat-pktrate');
  3366. if (bEl) bEl.value = '0 B';
  3367. if (pEl) pEl.value = '0';
  3368. if (rEl) rEl.value = '0 bps';
  3369. if (prEl) prEl.value = '0 p/s';
  3370. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3371. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3372. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3373. }
  3374. async function resetAllFwCounters() {
  3375. try {
  3376. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3377. if (res.ok) {
  3378. resetCurrentRuleCounters();
  3379. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3380. loadFirewall(false);
  3381. }
  3382. } catch (err) {
  3383. showToast('Error', err.message, 'error');
  3384. }
  3385. }
  3386. async function applyFilterRule(closeAfter = false) {
  3387. const id = document.getElementById('filter-modal-id').value;
  3388. const chain = document.getElementById('filter-modal-chain').value;
  3389. const action = document.getElementById('filter-modal-action').value;
  3390. const comment = document.getElementById('filter-modal-comment').value.trim();
  3391. const enabled = document.getElementById('filter-modal-enabled').checked;
  3392. const src = getFwFieldVal('src', true);
  3393. const dst = getFwFieldVal('dst', true);
  3394. const srclist = getFwFieldVal('srclist', true);
  3395. const dstlist = getFwFieldVal('dstlist', true);
  3396. const srcgeo = getFwFieldVal('srcgeo', true);
  3397. const dstgeo = getFwFieldVal('dstgeo', true);
  3398. const proto = getFwFieldVal('proto', true);
  3399. const sport = getFwFieldVal('sport', true);
  3400. const dport = getFwFieldVal('dport', true);
  3401. const anyport = getFwFieldVal('anyport', true);
  3402. const iniface = getFwFieldVal('iniface', true);
  3403. const outiface = getFwFieldVal('outiface', true);
  3404. const inifacelist = getFwFieldVal('inifacelist', true);
  3405. const outifacelist = getFwFieldVal('outifacelist', true);
  3406. const pktmark = getFwFieldVal('pktmark', true);
  3407. const connmark = getFwFieldVal('connmark', true);
  3408. const routingmark = getFwFieldVal('routingmark', true);
  3409. const conntype = getFwFieldVal('conntype', false);
  3410. const states = [];
  3411. const csBox = document.getElementById('fw-field-cs');
  3412. if (csBox && !csBox.classList.contains('hidden')) {
  3413. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3414. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3415. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3416. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3417. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3418. }
  3419. const natStates = [];
  3420. const natBox = document.getElementById('fw-field-natstate');
  3421. if (natBox && !natBox.classList.contains('hidden')) {
  3422. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3423. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3424. }
  3425. const payload = {
  3426. id,
  3427. chain,
  3428. action,
  3429. protocol: proto || 'all',
  3430. src_address: src,
  3431. dst_address: dst,
  3432. src_port: sport,
  3433. dst_port: dport,
  3434. any_port: anyport,
  3435. in_interface: iniface,
  3436. out_interface: outiface,
  3437. in_interface_list: inifacelist,
  3438. out_interface_list: outifacelist,
  3439. packet_mark: pktmark,
  3440. connection_mark: connmark,
  3441. routing_mark: routingmark,
  3442. connection_type: conntype,
  3443. connection_state: states,
  3444. connection_nat_state: natStates,
  3445. src_address_list: srclist,
  3446. dst_address_list: dstlist,
  3447. src_geoip: srcgeo,
  3448. dst_geoip: dstgeo,
  3449. comment,
  3450. disabled: !enabled,
  3451. // Advanced tab
  3452. layer7_protocol: getFwFieldVal('layer7', false),
  3453. content: getFwFieldVal('content', false),
  3454. connection_bytes: getFwFieldVal('connbytes', false),
  3455. connection_rate: getFwFieldVal('connrate', false),
  3456. pcc: getFwFieldVal('pcc', false),
  3457. src_mac_address: getFwFieldVal('srcmac', true),
  3458. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3459. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3460. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3461. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3462. ipsec_policy: getFwFieldVal('ipsec', false),
  3463. tls_host: getFwFieldVal('tlshost', false),
  3464. ingress_priority: getFwFieldVal('ingresspriority', false),
  3465. priority: getFwFieldVal('priority', false),
  3466. dscp: getFwFieldVal('dscp', false),
  3467. tcp_mss: getFwFieldVal('tcpmss', false),
  3468. tos: document.getElementById('fw-val-tos')?.value || '',
  3469. packet_size: getFwFieldVal('pktsize', false),
  3470. random: getFwFieldVal('random', false),
  3471. tcp_flags: getFwFieldVal('tcpflags', false),
  3472. icmp_options: getFwFieldVal('icmpoptions', false),
  3473. ipv4_options: getFwFieldVal('ipv4options', false),
  3474. ttl: getFwFieldVal('ttl', false),
  3475. // Extra tab
  3476. time: getFwFieldVal('time', false),
  3477. limit: getFwFieldVal('limit', false),
  3478. dst_limit: getFwFieldVal('dstlimit', false),
  3479. psd: getFwFieldVal('psd', false),
  3480. // Action tab
  3481. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3482. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3483. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3484. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3485. log: document.getElementById('filter-modal-log')?.checked || false,
  3486. log_prefix: getFwFieldVal('logprefix', false)
  3487. };
  3488. try {
  3489. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3490. method: 'POST',
  3491. headers: { 'Content-Type': 'application/json' },
  3492. body: JSON.stringify(payload)
  3493. });
  3494. if (res.ok) {
  3495. const data = await res.json();
  3496. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3497. loadFirewall(false);
  3498. if (closeAfter) {
  3499. closeFilterModal();
  3500. } else {
  3501. if (data.id) {
  3502. document.getElementById('filter-modal-id').value = data.id;
  3503. const badge = document.getElementById('fw-modal-badge');
  3504. if (badge) badge.innerText = `#${data.id}`;
  3505. }
  3506. }
  3507. } else {
  3508. const err = await res.json();
  3509. showToast('Error', err.message || 'Failed to save rule', 'error');
  3510. }
  3511. } catch (err) {
  3512. showToast('Error', err.message, 'error');
  3513. }
  3514. }
  3515. function submitSaveFilterRule(e) {
  3516. if (e && e.preventDefault) e.preventDefault();
  3517. return applyFilterRule(true);
  3518. }
  3519. function startFwStatPolling() {
  3520. stopFwStatPolling();
  3521. pollRuleStats();
  3522. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3523. }
  3524. function stopFwStatPolling() {
  3525. if (state.fwStatInterval) {
  3526. clearInterval(state.fwStatInterval);
  3527. state.fwStatInterval = null;
  3528. }
  3529. }
  3530. async function pollRuleStats() {
  3531. const id = document.getElementById('filter-modal-id')?.value;
  3532. if (!id) {
  3533. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3534. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3535. return;
  3536. }
  3537. try {
  3538. const res = await fetch(`${API_BASE}/firewall/filter`);
  3539. if (!res.ok) return;
  3540. const rules = await res.json();
  3541. const r = rules.find(x => x.id === id);
  3542. if (!r) return;
  3543. const now = Date.now();
  3544. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3545. state.fwLastTimestamp = now;
  3546. const curBytes = r.bytes || 0;
  3547. const curPackets = r.packets || 0;
  3548. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3549. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3550. state.fwLastBytes = curBytes;
  3551. state.fwLastPackets = curPackets;
  3552. const rateBps = Math.round((deltaBytes * 8) / dt);
  3553. const ratePkt = Math.round(deltaPkts / dt);
  3554. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3555. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3556. state.fwStatRateHistory.push(rateBps);
  3557. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3558. state.fwStatPktHistory.push(ratePkt);
  3559. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3560. const bEl = document.getElementById('fw-stat-bytes');
  3561. const pEl = document.getElementById('fw-stat-packets');
  3562. const rEl = document.getElementById('fw-stat-rate');
  3563. const prEl = document.getElementById('fw-stat-pktrate');
  3564. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3565. if (pEl) pEl.value = curPackets.toLocaleString();
  3566. if (rEl) rEl.value = formatBps(rateBps);
  3567. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3568. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3569. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3570. } catch (e) {
  3571. console.error('Error polling rule stats', e);
  3572. }
  3573. }
  3574. function formatBps(bps) {
  3575. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3576. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3577. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3578. return bps + ' bps';
  3579. }
  3580. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3581. const svg = document.getElementById(svgId);
  3582. if (!svg) return;
  3583. const w = 500;
  3584. const h = 100;
  3585. const paddingRight = 45;
  3586. const graphWidth = w - paddingRight;
  3587. const maxVal = Math.max(5, ...dataArray);
  3588. const currentVal = dataArray[dataArray.length - 1] || 0;
  3589. const leg = document.getElementById(legendId);
  3590. if (leg) {
  3591. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3592. }
  3593. let gridLines = '';
  3594. for (let i = 0; i <= 5; i++) {
  3595. const y = 8 + (i * (h - 18) / 5);
  3596. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3597. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3598. gridLines += `
  3599. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3600. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3601. `;
  3602. }
  3603. const step = graphWidth / (dataArray.length - 1);
  3604. const points = dataArray.map((val, idx) => {
  3605. const x = idx * step;
  3606. const y = (h - 10) - (val / maxVal) * (h - 20);
  3607. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3608. });
  3609. const polylineStr = points.join(' ');
  3610. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3611. svg.innerHTML = `
  3612. ${gridLines}
  3613. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3614. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3615. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3616. `;
  3617. }
  3618. async function moveFilterRule(id, dir) {
  3619. try {
  3620. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3621. method: 'POST',
  3622. headers: { 'Content-Type': 'application/json' },
  3623. body: JSON.stringify({ direction: dir })
  3624. });
  3625. if (res.ok) loadFirewall(false);
  3626. } catch (err) {
  3627. showToast('Error', err.message, 'error');
  3628. }
  3629. }
  3630. async function toggleFilterRuleState(id, disabled) {
  3631. try {
  3632. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3633. method: 'POST',
  3634. headers: { 'Content-Type': 'application/json' },
  3635. body: JSON.stringify({ disabled })
  3636. });
  3637. if (res.ok) loadFirewall(false);
  3638. } catch (err) {
  3639. showToast('Error', err.message, 'error');
  3640. }
  3641. }
  3642. async function deleteFilterRule(id) {
  3643. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3644. try {
  3645. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3646. if (res.ok) {
  3647. showToast('Deleted', 'Filter rule removed', 'success');
  3648. loadFirewall(false);
  3649. }
  3650. } catch (err) {
  3651. showToast('Error', err.message, 'error');
  3652. }
  3653. }
  3654. // ----------------- NAT Rules -----------------
  3655. function renderNATRules() {
  3656. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3657. const tbody = document.getElementById('nat-table-body');
  3658. const empty = document.getElementById('nat-empty');
  3659. if (!tbody) return;
  3660. tbody.innerHTML = '';
  3661. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3662. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3663. if (rules.length === 0) {
  3664. empty?.classList.remove('hidden');
  3665. return;
  3666. }
  3667. empty?.classList.add('hidden');
  3668. rules.forEach((r, idx) => {
  3669. const tr = document.createElement('tr');
  3670. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3671. let toTarget = '-';
  3672. if (r.action === 'jump') {
  3673. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3674. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3675. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3676. } else if (r.action === 'redirect') {
  3677. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3678. } else if (r.action === 'masquerade') {
  3679. 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>`;
  3680. } else if (r.action === 'log') {
  3681. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3682. } else {
  3683. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3684. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3685. }
  3686. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3687. tr.innerHTML = `
  3688. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3689. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3690. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3691. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3692. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3693. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3694. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3695. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3696. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3697. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3698. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3699. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3700. </td>
  3701. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3702. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3703. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3704. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3705. <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>
  3706. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3707. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3708. </td>
  3709. `;
  3710. tbody.appendChild(tr);
  3711. });
  3712. }
  3713. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3714. function switchNATRuleTab(tab) {
  3715. state.activeNATRuleTab = tab;
  3716. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3717. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3718. btn.classList.add('text-slate-400', 'border-transparent');
  3719. });
  3720. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3721. if (activeBtn) {
  3722. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3723. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3724. }
  3725. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3726. const activePane = document.getElementById(`nat-pane-${tab}`);
  3727. if (activePane) activePane.classList.remove('hidden');
  3728. if (tab === 'statistics') {
  3729. startNATStatPolling();
  3730. } else {
  3731. stopNATStatPolling();
  3732. }
  3733. }
  3734. function toggleNATField(fieldKey, expand) {
  3735. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3736. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3737. if (!plusBtn || !fieldBox) return;
  3738. if (expand) {
  3739. plusBtn.classList.add('hidden');
  3740. fieldBox.classList.remove('hidden');
  3741. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3742. if (valInput) valInput.focus();
  3743. } else {
  3744. fieldBox.classList.add('hidden');
  3745. plusBtn.classList.remove('hidden');
  3746. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3747. if (valInput) {
  3748. if (valInput.tagName === 'SELECT') {
  3749. valInput.selectedIndex = 0;
  3750. } else {
  3751. valInput.value = '';
  3752. }
  3753. }
  3754. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3755. if (invInput) invInput.checked = false;
  3756. if (fieldKey === 'days') {
  3757. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3758. const el = document.getElementById(`nat-day-${d}`);
  3759. if (el) el.checked = true;
  3760. });
  3761. }
  3762. }
  3763. }
  3764. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3765. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3766. toggleNATField(fieldKey, true);
  3767. let strVal = String(value);
  3768. if (hasInvert) {
  3769. const inv = strVal.startsWith('!');
  3770. if (inv) strVal = strVal.slice(1);
  3771. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3772. if (invEl) invEl.checked = inv;
  3773. }
  3774. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3775. if (valEl) valEl.value = strVal;
  3776. } else {
  3777. toggleNATField(fieldKey, false);
  3778. }
  3779. }
  3780. function getNATFieldVal(fieldKey, hasInvert = false) {
  3781. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3782. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3783. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3784. let v = valEl ? valEl.value.trim() : '';
  3785. if (!v) return '';
  3786. if (hasInvert) {
  3787. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3788. if (invEl && invEl.checked) {
  3789. v = '!' + v.replace(/^!/, '');
  3790. }
  3791. }
  3792. return v;
  3793. }
  3794. function toggleMaximizeNATModal() {
  3795. const win = document.getElementById('nat-modal-window');
  3796. if (!win) return;
  3797. if (win.classList.contains('max-w-[720px]')) {
  3798. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3799. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3800. } else {
  3801. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3802. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3803. }
  3804. }
  3805. function handleNATChainChange() {
  3806. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3807. const actSel = document.getElementById('nat-modal-action');
  3808. if (actSel) {
  3809. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3810. actSel.value = 'masquerade';
  3811. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3812. actSel.value = 'dst-nat';
  3813. }
  3814. }
  3815. toggleNATActionFields();
  3816. }
  3817. function toggleNATActionFields() {
  3818. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3819. const rowAddr = document.getElementById('nat-row-toaddr');
  3820. const rowPort = document.getElementById('nat-row-toport');
  3821. const jumpBox = document.getElementById('nat-action-jump-box');
  3822. const addrBox = document.getElementById('nat-action-addrlist-box');
  3823. // Hide all dynamic rows first
  3824. if (rowAddr) rowAddr.classList.add('hidden');
  3825. if (rowPort) rowPort.classList.add('hidden');
  3826. if (jumpBox) jumpBox.classList.add('hidden');
  3827. if (addrBox) addrBox.classList.add('hidden');
  3828. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3829. if (rowAddr) rowAddr.classList.remove('hidden');
  3830. if (rowPort) rowPort.classList.remove('hidden');
  3831. } else if (act === 'redirect' || act === 'masquerade') {
  3832. if (rowPort) rowPort.classList.remove('hidden');
  3833. } else if (act === 'jump') {
  3834. if (jumpBox) jumpBox.classList.remove('hidden');
  3835. } else if (act.includes('address-list') || act.includes('address list')) {
  3836. if (addrBox) addrBox.classList.remove('hidden');
  3837. }
  3838. if (act === 'log') {
  3839. const logEl = document.getElementById('nat-modal-log');
  3840. if (logEl) logEl.checked = true;
  3841. toggleNATField('logprefix', true);
  3842. }
  3843. }
  3844. function toggleNATLogPrefix() {
  3845. const isLog = document.getElementById('nat-modal-log')?.checked;
  3846. toggleNATField('logprefix', !!isLog);
  3847. }
  3848. function openAddNATModal() {
  3849. switchNATRuleTab('general');
  3850. const badge = document.getElementById('nat-modal-badge');
  3851. if (badge) badge.innerText = 'New...';
  3852. document.getElementById('nat-modal-id').value = '';
  3853. document.getElementById('nat-modal-enabled').checked = true;
  3854. document.getElementById('nat-modal-comment').value = '';
  3855. document.getElementById('nat-modal-chain').value = 'srcnat';
  3856. document.getElementById('nat-modal-action').value = 'masquerade';
  3857. document.getElementById('nat-modal-toaddr').value = '';
  3858. document.getElementById('nat-modal-toport').value = '';
  3859. document.getElementById('nat-modal-log').checked = false;
  3860. populateInterfaceSelect('nat-val-iniface');
  3861. populateInterfaceSelect('nat-val-outiface');
  3862. populateAddressListSelect('nat-val-srclist');
  3863. populateAddressListSelect('nat-val-dstlist');
  3864. populateGeoIPSelect('nat-val-srcgeo');
  3865. populateGeoIPSelect('nat-val-dstgeo');
  3866. const allFieldKeys = [
  3867. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3868. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3869. 'routingmark', 'conntype',
  3870. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3871. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3872. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3873. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3874. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3875. ];
  3876. allFieldKeys.forEach(k => toggleNATField(k, false));
  3877. resetCurrentNATRuleCounters();
  3878. toggleNATActionFields();
  3879. document.getElementById('nat-modal').classList.remove('hidden');
  3880. }
  3881. function openEditNATModal(id) {
  3882. const r = (state.natRules || []).find(rule => rule.id === id);
  3883. if (!r) return;
  3884. switchNATRuleTab('general');
  3885. const badge = document.getElementById('nat-modal-badge');
  3886. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3887. document.getElementById('nat-modal-id').value = r.id;
  3888. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3889. document.getElementById('nat-modal-comment').value = r.comment || '';
  3890. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3891. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3892. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3893. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3894. document.getElementById('nat-modal-log').checked = !!r.log;
  3895. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3896. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3897. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3898. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3899. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3900. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3901. setNATFieldVal('src', r.src_address, true);
  3902. setNATFieldVal('dst', r.dst_address, true);
  3903. setNATFieldVal('srclist', r.src_address_list, true);
  3904. setNATFieldVal('dstlist', r.dst_address_list, true);
  3905. setNATFieldVal('srcgeo', r.src_geoip, true);
  3906. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3907. if (r.protocol && r.protocol !== 'all') {
  3908. setNATFieldVal('proto', r.protocol, true);
  3909. } else {
  3910. toggleNATField('proto', false);
  3911. }
  3912. setNATFieldVal('sport', r.src_port, true);
  3913. setNATFieldVal('dport', r.dst_port, true);
  3914. setNATFieldVal('anyport', r.any_port, true);
  3915. setNATFieldVal('iniface', r.in_interface, true);
  3916. setNATFieldVal('outiface', r.out_interface, true);
  3917. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3918. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3919. setNATFieldVal('pktmark', r.packet_mark, true);
  3920. setNATFieldVal('connmark', r.connection_mark, true);
  3921. setNATFieldVal('routingmark', r.routing_mark, true);
  3922. setNATFieldVal('conntype', r.connection_type, false);
  3923. // Advanced tab fields
  3924. setNATFieldVal('layer7', r.layer7_protocol, false);
  3925. setNATFieldVal('content', r.content, false);
  3926. setNATFieldVal('connbytes', r.connection_bytes, false);
  3927. setNATFieldVal('connrate', r.connection_rate, false);
  3928. setNATFieldVal('pcc', r.pcc, false);
  3929. setNATFieldVal('srcmac', r.src_mac_address, true);
  3930. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3931. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3932. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3933. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3934. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3935. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3936. setNATFieldVal('priority', r.priority, false);
  3937. setNATFieldVal('dscp', r.dscp, false);
  3938. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3939. if (r.tos) {
  3940. const tosEl = document.getElementById('nat-val-tos');
  3941. if (tosEl) tosEl.value = r.tos;
  3942. }
  3943. setNATFieldVal('pktsize', r.packet_size, false);
  3944. setNATFieldVal('random', r.random, false);
  3945. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3946. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3947. setNATFieldVal('ttl', r.ttl, false);
  3948. // Extra tab fields
  3949. setNATFieldVal('time', r.time, false);
  3950. if (r.days) {
  3951. toggleNATField('days', true);
  3952. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3953. const chk = document.getElementById(`nat-day-${d}`);
  3954. if (chk) chk.checked = r.days.includes(d);
  3955. });
  3956. } else {
  3957. toggleNATField('days', false);
  3958. }
  3959. setNATFieldVal('limit', r.limit, false);
  3960. setNATFieldVal('dstlimit', r.dst_limit, false);
  3961. setNATFieldVal('psd', r.psd, false);
  3962. // Action fields
  3963. if (r.jump_target) {
  3964. const jtEl = document.getElementById('nat-modal-jumptarget');
  3965. if (jtEl) jtEl.value = r.jump_target;
  3966. }
  3967. if (r.address_list) {
  3968. const alEl = document.getElementById('nat-modal-action-addrlist');
  3969. if (alEl) alEl.value = r.address_list;
  3970. }
  3971. if (r.address_list_timeout) {
  3972. const toEl = document.getElementById('nat-modal-action-timeout');
  3973. if (toEl) toEl.value = r.address_list_timeout;
  3974. }
  3975. setNATFieldVal('logprefix', r.log_prefix, false);
  3976. // Statistics
  3977. const bEl = document.getElementById('nat-stat-bytes');
  3978. const pEl = document.getElementById('nat-stat-packets');
  3979. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3980. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3981. state.natLastBytes = r.bytes || 0;
  3982. state.natLastPackets = r.packets || 0;
  3983. state.natLastTimestamp = Date.now();
  3984. state.natStatRateHistory = new Array(30).fill(0);
  3985. state.natStatPktHistory = new Array(30).fill(0);
  3986. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3987. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3988. toggleNATActionFields();
  3989. document.getElementById('nat-modal').classList.remove('hidden');
  3990. }
  3991. function closeNATModal() {
  3992. stopNATStatPolling();
  3993. document.getElementById('nat-modal').classList.add('hidden');
  3994. }
  3995. function copyNATRule() {
  3996. document.getElementById('nat-modal-id').value = '';
  3997. const badge = document.getElementById('nat-modal-badge');
  3998. if (badge) badge.innerText = 'New...';
  3999. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4000. }
  4001. function resetCurrentNATRuleCounters() {
  4002. state.natStatRateHistory = new Array(30).fill(0);
  4003. state.natStatPktHistory = new Array(30).fill(0);
  4004. state.natLastBytes = 0;
  4005. state.natLastPackets = 0;
  4006. state.natLastTimestamp = Date.now();
  4007. const bEl = document.getElementById('nat-stat-bytes');
  4008. const pEl = document.getElementById('nat-stat-packets');
  4009. const rEl = document.getElementById('nat-stat-rate');
  4010. const prEl = document.getElementById('nat-stat-pktrate');
  4011. if (bEl) bEl.value = '0 B';
  4012. if (pEl) pEl.value = '0';
  4013. if (rEl) rEl.value = '0 bps';
  4014. if (prEl) prEl.value = '0 p/s';
  4015. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4016. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4017. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4018. }
  4019. async function applyNATRule(closeAfter = false) {
  4020. const id = document.getElementById('nat-modal-id').value;
  4021. const chain = document.getElementById('nat-modal-chain').value;
  4022. const action = document.getElementById('nat-modal-action').value;
  4023. const comment = document.getElementById('nat-modal-comment').value.trim();
  4024. const enabled = document.getElementById('nat-modal-enabled').checked;
  4025. const src = getNATFieldVal('src', true);
  4026. const dst = getNATFieldVal('dst', true);
  4027. const srclist = getNATFieldVal('srclist', true);
  4028. const dstlist = getNATFieldVal('dstlist', true);
  4029. const srcgeo = getNATFieldVal('srcgeo', true);
  4030. const dstgeo = getNATFieldVal('dstgeo', true);
  4031. const proto = getNATFieldVal('proto', true);
  4032. const sport = getNATFieldVal('sport', true);
  4033. const dport = getNATFieldVal('dport', true);
  4034. const anyport = getNATFieldVal('anyport', true);
  4035. const iniface = getNATFieldVal('iniface', true);
  4036. const outiface = getNATFieldVal('outiface', true);
  4037. const inifacelist = getNATFieldVal('inifacelist', true);
  4038. const outifacelist = getNATFieldVal('outifacelist', true);
  4039. const pktmark = getNATFieldVal('pktmark', true);
  4040. const connmark = getNATFieldVal('connmark', true);
  4041. const routingmark = getNATFieldVal('routingmark', true);
  4042. const conntype = getNATFieldVal('conntype', false);
  4043. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4044. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4045. const payload = {
  4046. id,
  4047. chain,
  4048. action,
  4049. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4050. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4051. protocol: proto || 'all',
  4052. src_address: src,
  4053. dst_address: dst,
  4054. src_port: sport,
  4055. dst_port: dport,
  4056. any_port: anyport,
  4057. in_interface: iniface,
  4058. out_interface: outiface,
  4059. in_interface_list: inifacelist,
  4060. out_interface_list: outifacelist,
  4061. packet_mark: pktmark,
  4062. connection_mark: connmark,
  4063. routing_mark: routingmark,
  4064. connection_type: conntype,
  4065. src_address_list: srclist,
  4066. dst_address_list: dstlist,
  4067. src_geoip: srcgeo,
  4068. dst_geoip: dstgeo,
  4069. comment,
  4070. disabled: !enabled,
  4071. // Advanced tab
  4072. layer7_protocol: getNATFieldVal('layer7', false),
  4073. content: getNATFieldVal('content', false),
  4074. connection_bytes: getNATFieldVal('connbytes', false),
  4075. connection_rate: getNATFieldVal('connrate', false),
  4076. pcc: getNATFieldVal('pcc', false),
  4077. src_mac_address: getNATFieldVal('srcmac', true),
  4078. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4079. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4080. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4081. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4082. ipsec_policy: getNATFieldVal('ipsec', false),
  4083. ingress_priority: getNATFieldVal('ingresspriority', false),
  4084. priority: getNATFieldVal('priority', false),
  4085. dscp: getNATFieldVal('dscp', false),
  4086. tcp_mss: getNATFieldVal('tcpmss', false),
  4087. tos: document.getElementById('nat-val-tos')?.value || '',
  4088. packet_size: getNATFieldVal('pktsize', false),
  4089. random: getNATFieldVal('random', false),
  4090. icmp_options: getNATFieldVal('icmpoptions', false),
  4091. ipv4_options: getNATFieldVal('ipv4options', false),
  4092. ttl: getNATFieldVal('ttl', false),
  4093. // Extra tab
  4094. time: getNATFieldVal('time', false),
  4095. limit: getNATFieldVal('limit', false),
  4096. dst_limit: getNATFieldVal('dstlimit', false),
  4097. psd: getNATFieldVal('psd', false),
  4098. // Action tab
  4099. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4100. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4101. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4102. log: document.getElementById('nat-modal-log')?.checked || false,
  4103. log_prefix: getNATFieldVal('logprefix', false)
  4104. };
  4105. try {
  4106. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4107. method: 'POST',
  4108. headers: { 'Content-Type': 'application/json' },
  4109. body: JSON.stringify(payload)
  4110. });
  4111. if (res.ok) {
  4112. const data = await res.json();
  4113. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4114. loadFirewall(false);
  4115. if (closeAfter) {
  4116. closeNATModal();
  4117. } else {
  4118. if (data.id) {
  4119. document.getElementById('nat-modal-id').value = data.id;
  4120. const badge = document.getElementById('nat-modal-badge');
  4121. if (badge) badge.innerText = `#${data.id}`;
  4122. }
  4123. }
  4124. } else {
  4125. const err = await res.json();
  4126. showToast('Error', err.message || 'Failed to save rule', 'error');
  4127. }
  4128. } catch (err) {
  4129. showToast('Error', err.message, 'error');
  4130. }
  4131. }
  4132. function submitSaveNATRule(e) {
  4133. if (e && e.preventDefault) e.preventDefault();
  4134. return applyNATRule(true);
  4135. }
  4136. function startNATStatPolling() {
  4137. stopNATStatPolling();
  4138. pollNATRuleStats();
  4139. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4140. }
  4141. function stopNATStatPolling() {
  4142. if (state.natStatInterval) {
  4143. clearInterval(state.natStatInterval);
  4144. state.natStatInterval = null;
  4145. }
  4146. }
  4147. async function pollNATRuleStats() {
  4148. const id = document.getElementById('nat-modal-id')?.value;
  4149. if (!id) {
  4150. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4151. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4152. return;
  4153. }
  4154. try {
  4155. const res = await fetch(`${API_BASE}/firewall/nat`);
  4156. if (!res.ok) return;
  4157. const rules = await res.json();
  4158. const r = rules.find(x => x.id === id);
  4159. if (!r) return;
  4160. const now = Date.now();
  4161. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4162. state.natLastTimestamp = now;
  4163. const curBytes = r.bytes || 0;
  4164. const curPackets = r.packets || 0;
  4165. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4166. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4167. state.natLastBytes = curBytes;
  4168. state.natLastPackets = curPackets;
  4169. const rateBps = Math.round((deltaBytes * 8) / dt);
  4170. const ratePkt = Math.round(deltaPkts / dt);
  4171. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4172. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4173. state.natStatRateHistory.push(rateBps);
  4174. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4175. state.natStatPktHistory.push(ratePkt);
  4176. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4177. const bEl = document.getElementById('nat-stat-bytes');
  4178. const pEl = document.getElementById('nat-stat-packets');
  4179. const rEl = document.getElementById('nat-stat-rate');
  4180. const prEl = document.getElementById('nat-stat-pktrate');
  4181. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4182. if (pEl) pEl.value = curPackets.toLocaleString();
  4183. if (rEl) rEl.value = formatBps(rateBps);
  4184. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4185. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4186. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4187. } catch (e) {
  4188. console.error('Error polling NAT rule stats', e);
  4189. }
  4190. }
  4191. async function moveNATRule(id, dir) {
  4192. try {
  4193. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4194. method: 'POST',
  4195. headers: { 'Content-Type': 'application/json' },
  4196. body: JSON.stringify({ direction: dir })
  4197. });
  4198. if (res.ok) loadFirewall(false);
  4199. } catch (err) {
  4200. showToast('Error', err.message, 'error');
  4201. }
  4202. }
  4203. async function toggleNATRuleState(id, disabled) {
  4204. try {
  4205. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4206. method: 'POST',
  4207. headers: { 'Content-Type': 'application/json' },
  4208. body: JSON.stringify({ disabled })
  4209. });
  4210. if (res.ok) loadFirewall(false);
  4211. } catch (err) {
  4212. showToast('Error', err.message, 'error');
  4213. }
  4214. }
  4215. async function deleteNATRule(id) {
  4216. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4217. try {
  4218. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4219. if (res.ok) {
  4220. showToast('Deleted', 'NAT rule removed', 'success');
  4221. loadFirewall(false);
  4222. }
  4223. } catch (err) {
  4224. showToast('Error', err.message, 'error');
  4225. }
  4226. }
  4227. // ----------------- Mangle Rules -----------------
  4228. function renderMangleRules() {
  4229. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4230. const tbody = document.getElementById('mangle-table-body');
  4231. const empty = document.getElementById('mangle-empty');
  4232. if (!tbody) return;
  4233. tbody.innerHTML = '';
  4234. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4235. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4236. if (rules.length === 0) {
  4237. empty?.classList.remove('hidden');
  4238. return;
  4239. }
  4240. empty?.classList.add('hidden');
  4241. rules.forEach((r, idx) => {
  4242. const tr = document.createElement('tr');
  4243. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4244. let markVal = '<span class="text-slate-500">-</span>';
  4245. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4246. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4247. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4248. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4249. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4250. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4251. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4252. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4253. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4254. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4255. 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>`;
  4256. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4257. tr.innerHTML = `
  4258. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4259. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4260. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4261. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4262. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4263. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4264. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4265. <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>
  4266. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4267. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4268. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4269. </td>
  4270. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4271. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4272. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4273. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4274. <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>
  4275. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4276. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4277. </td>
  4278. `;
  4279. tbody.appendChild(tr);
  4280. });
  4281. }
  4282. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4283. function switchMangleRuleTab(tab) {
  4284. state.activeMangleRuleTab = tab;
  4285. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4286. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4287. btn.classList.add('text-slate-400', 'border-transparent');
  4288. });
  4289. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4290. if (activeBtn) {
  4291. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4292. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4293. }
  4294. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4295. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4296. if (activePane) activePane.classList.remove('hidden');
  4297. if (tab === 'statistics') {
  4298. startMangleStatPolling();
  4299. } else {
  4300. stopMangleStatPolling();
  4301. }
  4302. }
  4303. function toggleMangleField(fieldKey, expand) {
  4304. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4305. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4306. if (!plusBtn || !fieldBox) return;
  4307. if (expand) {
  4308. plusBtn.classList.add('hidden');
  4309. fieldBox.classList.remove('hidden');
  4310. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4311. if (valInput) valInput.focus();
  4312. } else {
  4313. fieldBox.classList.add('hidden');
  4314. plusBtn.classList.remove('hidden');
  4315. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4316. if (valInput) {
  4317. if (valInput.tagName === 'SELECT') {
  4318. valInput.selectedIndex = 0;
  4319. } else {
  4320. valInput.value = '';
  4321. }
  4322. }
  4323. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4324. if (invInput) invInput.checked = false;
  4325. if (fieldKey === 'cs') {
  4326. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4327. const el = document.getElementById(id);
  4328. if (el) el.checked = false;
  4329. });
  4330. }
  4331. if (fieldKey === 'natstate') {
  4332. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4333. const el = document.getElementById(id);
  4334. if (el) el.checked = false;
  4335. });
  4336. }
  4337. }
  4338. }
  4339. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4340. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4341. toggleMangleField(fieldKey, true);
  4342. let strVal = String(value);
  4343. if (hasInvert) {
  4344. const inv = strVal.startsWith('!');
  4345. if (inv) strVal = strVal.slice(1);
  4346. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4347. if (invEl) invEl.checked = inv;
  4348. }
  4349. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4350. if (valEl) valEl.value = strVal;
  4351. } else {
  4352. toggleMangleField(fieldKey, false);
  4353. }
  4354. }
  4355. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4356. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4357. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4358. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4359. let v = valEl ? valEl.value.trim() : '';
  4360. if (!v) return '';
  4361. if (hasInvert) {
  4362. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4363. if (invEl && invEl.checked) {
  4364. v = '!' + v.replace(/^!/, '');
  4365. }
  4366. }
  4367. return v;
  4368. }
  4369. function toggleMaximizeMangleModal() {
  4370. const win = document.getElementById('mangle-modal-window');
  4371. if (!win) return;
  4372. if (win.classList.contains('max-w-[720px]')) {
  4373. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4374. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4375. } else {
  4376. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4377. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4378. }
  4379. }
  4380. function toggleMangleActionFields() {
  4381. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4382. // Hide all dynamic rows first
  4383. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4384. const el = document.getElementById(`mangle-row-${id}`);
  4385. if (el) el.classList.add('hidden');
  4386. });
  4387. const jumpBox = document.getElementById('mangle-action-jump-box');
  4388. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4389. if (jumpBox) jumpBox.classList.add('hidden');
  4390. if (addrBox) addrBox.classList.add('hidden');
  4391. // Activate matching rows
  4392. if (act === 'mark-connection') {
  4393. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4394. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4395. } else if (act === 'mark-routing') {
  4396. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4397. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4398. } else if (act === 'mark-packet') {
  4399. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4400. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4401. } else if (act === 'change-mss') {
  4402. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4403. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4404. } else if (act === 'change-dscp') {
  4405. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4406. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4407. } else if (act === 'change-ttl') {
  4408. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4409. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4410. } else if (act === 'set-priority') {
  4411. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4412. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4413. } else if (act === 'route') {
  4414. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4415. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4416. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4417. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4418. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4419. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4420. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4421. } else if (act === 'jump') {
  4422. if (jumpBox) jumpBox.classList.remove('hidden');
  4423. } else if (act.includes('address-list') || act.includes('address list')) {
  4424. if (addrBox) addrBox.classList.remove('hidden');
  4425. }
  4426. if (act === 'log') {
  4427. const logEl = document.getElementById('mangle-modal-log');
  4428. if (logEl) logEl.checked = true;
  4429. toggleMangleField('logprefix', true);
  4430. }
  4431. }
  4432. function toggleMangleLogPrefix() {
  4433. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4434. toggleMangleField('logprefix', !!isLog);
  4435. }
  4436. const allMangleFieldKeys = [
  4437. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4438. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4439. 'routingmark', 'conntype', 'cs', 'natstate',
  4440. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4441. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4442. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4443. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4444. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4445. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4446. ];
  4447. function openAddMangleModal() {
  4448. switchMangleRuleTab('general');
  4449. const badge = document.getElementById('mangle-modal-badge');
  4450. if (badge) badge.innerText = 'New...';
  4451. document.getElementById('mangle-modal-id').value = '';
  4452. document.getElementById('mangle-modal-enabled').checked = true;
  4453. document.getElementById('mangle-modal-comment').value = '';
  4454. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4455. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4456. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4457. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4458. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4459. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4460. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4461. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4462. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4463. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4464. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4465. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4466. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4467. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4468. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4469. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4470. populateInterfaceSelect('mangle-val-iniface');
  4471. populateInterfaceSelect('mangle-val-outiface');
  4472. populateAddressListSelect('mangle-val-srclist');
  4473. populateAddressListSelect('mangle-val-dstlist');
  4474. populateGeoIPSelect('mangle-val-srcgeo');
  4475. populateGeoIPSelect('mangle-val-dstgeo');
  4476. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4477. resetCurrentMangleRuleCounters();
  4478. toggleMangleActionFields();
  4479. document.getElementById('mangle-modal').classList.remove('hidden');
  4480. }
  4481. function openEditMangleModal(id) {
  4482. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4483. if (!r) return;
  4484. switchMangleRuleTab('general');
  4485. const badge = document.getElementById('mangle-modal-badge');
  4486. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4487. document.getElementById('mangle-modal-id').value = r.id;
  4488. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4489. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4490. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4491. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4492. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4493. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4494. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4495. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4496. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4497. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4498. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4499. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4500. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4501. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4502. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4503. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4504. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4505. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4506. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4507. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4508. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4509. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4510. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4511. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4512. setMangleFieldVal('src', r.src_address, true);
  4513. setMangleFieldVal('dst', r.dst_address, true);
  4514. setMangleFieldVal('srclist', r.src_address_list, true);
  4515. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4516. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4517. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4518. if (r.protocol && r.protocol !== 'all') {
  4519. setMangleFieldVal('proto', r.protocol, true);
  4520. } else {
  4521. toggleMangleField('proto', false);
  4522. }
  4523. setMangleFieldVal('sport', r.src_port, true);
  4524. setMangleFieldVal('dport', r.dst_port, true);
  4525. setMangleFieldVal('anyport', r.any_port, true);
  4526. setMangleFieldVal('iniface', r.in_interface, true);
  4527. setMangleFieldVal('outiface', r.out_interface, true);
  4528. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4529. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4530. setMangleFieldVal('pktmark', r.packet_mark, true);
  4531. setMangleFieldVal('connmark', r.connection_mark, true);
  4532. setMangleFieldVal('routingmark', r.routing_mark, true);
  4533. setMangleFieldVal('conntype', r.connection_type, false);
  4534. // Connection State
  4535. const states = r.connection_state || [];
  4536. if (states.length > 0) {
  4537. toggleMangleField('cs', true);
  4538. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4539. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4540. if (el) el.checked = states.includes(s);
  4541. });
  4542. } else {
  4543. toggleMangleField('cs', false);
  4544. }
  4545. // Connection NAT State
  4546. const natStates = r.connection_nat_state || [];
  4547. if (natStates.length > 0) {
  4548. toggleMangleField('natstate', true);
  4549. ['srcnat', 'dstnat'].forEach(s => {
  4550. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4551. if (el) el.checked = natStates.includes(s);
  4552. });
  4553. } else {
  4554. toggleMangleField('natstate', false);
  4555. }
  4556. // Advanced tab fields
  4557. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4558. setMangleFieldVal('content', r.content, false);
  4559. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4560. setMangleFieldVal('connrate', r.connection_rate, false);
  4561. setMangleFieldVal('pcc', r.pcc, false);
  4562. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4563. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4564. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4565. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4566. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4567. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4568. setMangleFieldVal('tlshost', r.tls_host, false);
  4569. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4570. setMangleFieldVal('priority', r.priority, false);
  4571. setMangleFieldVal('dscp', r.dscp, false);
  4572. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4573. if (r.tos) {
  4574. const tosEl = document.getElementById('mangle-val-tos');
  4575. if (tosEl) tosEl.value = r.tos;
  4576. }
  4577. setMangleFieldVal('pktsize', r.packet_size, false);
  4578. setMangleFieldVal('random', r.random, false);
  4579. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4580. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4581. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4582. setMangleFieldVal('ttl', r.ttl, false);
  4583. // Extra tab fields
  4584. setMangleFieldVal('nth', r.nth, false);
  4585. setMangleFieldVal('connlimit', r.connection_limit, false);
  4586. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4587. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4588. setMangleFieldVal('hotspot', r.hotspot, false);
  4589. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4590. setMangleFieldVal('limit', r.limit, false);
  4591. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4592. setMangleFieldVal('time', r.time, false);
  4593. setMangleFieldVal('psd', r.psd, false);
  4594. // Action fields
  4595. if (r.jump_target) {
  4596. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4597. if (jtEl) jtEl.value = r.jump_target;
  4598. }
  4599. if (r.address_list) {
  4600. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4601. if (alEl) alEl.value = r.address_list;
  4602. }
  4603. if (r.address_list_timeout) {
  4604. const toEl = document.getElementById('mangle-modal-action-timeout');
  4605. if (toEl) toEl.value = r.address_list_timeout;
  4606. }
  4607. setMangleFieldVal('logprefix', r.log_prefix, false);
  4608. // Statistics
  4609. const bEl = document.getElementById('mangle-stat-bytes');
  4610. const pEl = document.getElementById('mangle-stat-packets');
  4611. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4612. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4613. state.mangleLastBytes = r.bytes || 0;
  4614. state.mangleLastPackets = r.packets || 0;
  4615. state.mangleLastTimestamp = Date.now();
  4616. state.mangleStatRateHistory = new Array(30).fill(0);
  4617. state.mangleStatPktHistory = new Array(30).fill(0);
  4618. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4619. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4620. toggleMangleActionFields();
  4621. document.getElementById('mangle-modal').classList.remove('hidden');
  4622. }
  4623. function closeMangleModal() {
  4624. stopMangleStatPolling();
  4625. document.getElementById('mangle-modal').classList.add('hidden');
  4626. }
  4627. function copyMangleRule() {
  4628. document.getElementById('mangle-modal-id').value = '';
  4629. const badge = document.getElementById('mangle-modal-badge');
  4630. if (badge) badge.innerText = 'New...';
  4631. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4632. }
  4633. function resetCurrentMangleRuleCounters() {
  4634. state.mangleStatRateHistory = new Array(30).fill(0);
  4635. state.mangleStatPktHistory = new Array(30).fill(0);
  4636. state.mangleLastBytes = 0;
  4637. state.mangleLastPackets = 0;
  4638. state.mangleLastTimestamp = Date.now();
  4639. const bEl = document.getElementById('mangle-stat-bytes');
  4640. const pEl = document.getElementById('mangle-stat-packets');
  4641. const rEl = document.getElementById('mangle-stat-rate');
  4642. const prEl = document.getElementById('mangle-stat-pktrate');
  4643. if (bEl) bEl.value = '0 B';
  4644. if (pEl) pEl.value = '0';
  4645. if (rEl) rEl.value = '0 bps';
  4646. if (prEl) prEl.value = '0 p/s';
  4647. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4648. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4649. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4650. }
  4651. async function applyMangleRule(closeAfter = false) {
  4652. const id = document.getElementById('mangle-modal-id').value;
  4653. const chain = document.getElementById('mangle-modal-chain').value;
  4654. const action = document.getElementById('mangle-modal-action').value;
  4655. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4656. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4657. const src = getMangleFieldVal('src', true);
  4658. const dst = getMangleFieldVal('dst', true);
  4659. const srclist = getMangleFieldVal('srclist', true);
  4660. const dstlist = getMangleFieldVal('dstlist', true);
  4661. const srcgeo = getMangleFieldVal('srcgeo', true);
  4662. const dstgeo = getMangleFieldVal('dstgeo', true);
  4663. const proto = getMangleFieldVal('proto', true);
  4664. const sport = getMangleFieldVal('sport', true);
  4665. const dport = getMangleFieldVal('dport', true);
  4666. const anyport = getMangleFieldVal('anyport', true);
  4667. const iniface = getMangleFieldVal('iniface', true);
  4668. const outiface = getMangleFieldVal('outiface', true);
  4669. const inifacelist = getMangleFieldVal('inifacelist', true);
  4670. const outifacelist = getMangleFieldVal('outifacelist', true);
  4671. const pktmark = getMangleFieldVal('pktmark', true);
  4672. const connmark = getMangleFieldVal('connmark', true);
  4673. const routingmark = getMangleFieldVal('routingmark', true);
  4674. const conntype = getMangleFieldVal('conntype', false);
  4675. const states = [];
  4676. const csBox = document.getElementById('mangle-field-cs');
  4677. if (csBox && !csBox.classList.contains('hidden')) {
  4678. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4679. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4680. });
  4681. }
  4682. const natStates = [];
  4683. const natBox = document.getElementById('mangle-field-natstate');
  4684. if (natBox && !natBox.classList.contains('hidden')) {
  4685. ['srcnat', 'dstnat'].forEach(s => {
  4686. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4687. });
  4688. }
  4689. const payload = {
  4690. id,
  4691. chain,
  4692. action,
  4693. protocol: proto || 'all',
  4694. src_address: src,
  4695. dst_address: dst,
  4696. src_port: sport,
  4697. dst_port: dport,
  4698. any_port: anyport,
  4699. in_interface: iniface,
  4700. out_interface: outiface,
  4701. in_interface_list: inifacelist,
  4702. out_interface_list: outifacelist,
  4703. packet_mark: pktmark,
  4704. connection_mark: connmark,
  4705. routing_mark: routingmark,
  4706. connection_type: conntype,
  4707. connection_state: states,
  4708. connection_nat_state: natStates,
  4709. src_address_list: srclist,
  4710. dst_address_list: dstlist,
  4711. src_geoip: srcgeo,
  4712. dst_geoip: dstgeo,
  4713. comment,
  4714. disabled: !enabled,
  4715. // Advanced tab
  4716. layer7_protocol: getMangleFieldVal('layer7', false),
  4717. content: getMangleFieldVal('content', false),
  4718. connection_bytes: getMangleFieldVal('connbytes', false),
  4719. connection_rate: getMangleFieldVal('connrate', false),
  4720. pcc: getMangleFieldVal('pcc', false),
  4721. src_mac_address: getMangleFieldVal('srcmac', true),
  4722. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4723. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4724. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4725. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4726. ipsec_policy: getMangleFieldVal('ipsec', false),
  4727. tls_host: getMangleFieldVal('tlshost', false),
  4728. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4729. priority: getMangleFieldVal('priority', false),
  4730. dscp: getMangleFieldVal('dscp', false),
  4731. tcp_mss: getMangleFieldVal('tcpmss', false),
  4732. tos: document.getElementById('mangle-val-tos')?.value || '',
  4733. packet_size: getMangleFieldVal('pktsize', false),
  4734. random: getMangleFieldVal('random', false),
  4735. tcp_flags: getMangleFieldVal('tcpflags', false),
  4736. icmp_options: getMangleFieldVal('icmpoptions', false),
  4737. ipv4_options: getMangleFieldVal('ipv4options', false),
  4738. ttl: getMangleFieldVal('ttl', false),
  4739. // Extra tab
  4740. nth: getMangleFieldVal('nth', false),
  4741. connection_limit: getMangleFieldVal('connlimit', false),
  4742. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4743. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4744. hotspot: getMangleFieldVal('hotspot', false),
  4745. ip_fragment: getMangleFieldVal('ipfragment', false),
  4746. limit: getMangleFieldVal('limit', false),
  4747. dst_limit: getMangleFieldVal('dstlimit', false),
  4748. time: getMangleFieldVal('time', false),
  4749. psd: getMangleFieldVal('psd', false),
  4750. // Action tab
  4751. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4752. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4753. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4754. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4755. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4756. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4757. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4758. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4759. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4760. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4761. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4762. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4763. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4764. log: document.getElementById('mangle-modal-log')?.checked || false,
  4765. log_prefix: getMangleFieldVal('logprefix', false)
  4766. };
  4767. try {
  4768. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4769. method: 'POST',
  4770. headers: { 'Content-Type': 'application/json' },
  4771. body: JSON.stringify(payload)
  4772. });
  4773. if (res.ok) {
  4774. const data = await res.json();
  4775. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4776. loadFirewall(false);
  4777. if (closeAfter) {
  4778. closeMangleModal();
  4779. } else {
  4780. if (data.id) {
  4781. document.getElementById('mangle-modal-id').value = data.id;
  4782. const badge = document.getElementById('mangle-modal-badge');
  4783. if (badge) badge.innerText = `#${data.id}`;
  4784. }
  4785. }
  4786. } else {
  4787. const err = await res.json();
  4788. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4789. }
  4790. } catch (err) {
  4791. showToast('Error', err.message, 'error');
  4792. }
  4793. }
  4794. function submitSaveMangleRule(e) {
  4795. if (e && e.preventDefault) e.preventDefault();
  4796. return applyMangleRule(true);
  4797. }
  4798. function startMangleStatPolling() {
  4799. stopMangleStatPolling();
  4800. pollMangleRuleStats();
  4801. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4802. }
  4803. function stopMangleStatPolling() {
  4804. if (state.mangleStatInterval) {
  4805. clearInterval(state.mangleStatInterval);
  4806. state.mangleStatInterval = null;
  4807. }
  4808. }
  4809. async function pollMangleRuleStats() {
  4810. const id = document.getElementById('mangle-modal-id')?.value;
  4811. if (!id) {
  4812. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4813. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4814. return;
  4815. }
  4816. try {
  4817. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4818. if (!res.ok) return;
  4819. const rules = await res.json();
  4820. const r = rules.find(x => x.id === id);
  4821. if (!r) return;
  4822. const now = Date.now();
  4823. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4824. state.mangleLastTimestamp = now;
  4825. const curBytes = r.bytes || 0;
  4826. const curPackets = r.packets || 0;
  4827. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4828. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4829. state.mangleLastBytes = curBytes;
  4830. state.mangleLastPackets = curPackets;
  4831. const rateBps = Math.round((deltaBytes * 8) / dt);
  4832. const ratePkt = Math.round(deltaPkts / dt);
  4833. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4834. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4835. state.mangleStatRateHistory.push(rateBps);
  4836. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4837. state.mangleStatPktHistory.push(ratePkt);
  4838. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4839. const bEl = document.getElementById('mangle-stat-bytes');
  4840. const pEl = document.getElementById('mangle-stat-packets');
  4841. const rEl = document.getElementById('mangle-stat-rate');
  4842. const prEl = document.getElementById('mangle-stat-pktrate');
  4843. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4844. if (pEl) pEl.value = curPackets.toLocaleString();
  4845. if (rEl) rEl.value = formatBps(rateBps);
  4846. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4847. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4848. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4849. } catch (e) {
  4850. console.error('Error polling Mangle rule stats', e);
  4851. }
  4852. }
  4853. async function moveMangleRule(id, dir) {
  4854. try {
  4855. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4856. method: 'POST',
  4857. headers: { 'Content-Type': 'application/json' },
  4858. body: JSON.stringify({ direction: dir })
  4859. });
  4860. if (res.ok) loadFirewall(false);
  4861. } catch (err) {
  4862. showToast('Error', err.message, 'error');
  4863. }
  4864. }
  4865. async function toggleMangleRuleState(id, disabled) {
  4866. try {
  4867. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4868. method: 'POST',
  4869. headers: { 'Content-Type': 'application/json' },
  4870. body: JSON.stringify({ disabled })
  4871. });
  4872. if (res.ok) loadFirewall(false);
  4873. } catch (err) {
  4874. showToast('Error', err.message, 'error');
  4875. }
  4876. }
  4877. async function deleteMangleRule(id) {
  4878. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4879. try {
  4880. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4881. if (res.ok) {
  4882. showToast('Deleted', 'Mangle rule removed', 'success');
  4883. loadFirewall(false);
  4884. }
  4885. } catch (err) {
  4886. showToast('Error', err.message, 'error');
  4887. }
  4888. }
  4889. // ----------------- Address Lists -----------------
  4890. function renderAddressLists() {
  4891. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4892. const tbody = document.getElementById('addrlist-table-body');
  4893. const empty = document.getElementById('addrlist-empty');
  4894. if (!tbody) return;
  4895. tbody.innerHTML = '';
  4896. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4897. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4898. // Update filter select
  4899. const sel = document.getElementById('addrlist-filter-name');
  4900. if (sel) {
  4901. const cur = sel.value;
  4902. sel.innerHTML = '<option value="">All Lists</option>';
  4903. const set = new Set((state.addressLists || []).map(a => a.name));
  4904. set.forEach(n => {
  4905. const opt = document.createElement('option');
  4906. opt.value = n;
  4907. opt.innerText = n;
  4908. if (n === cur) opt.selected = true;
  4909. sel.appendChild(opt);
  4910. });
  4911. }
  4912. if (entries.length === 0) {
  4913. empty?.classList.remove('hidden');
  4914. return;
  4915. }
  4916. empty?.classList.add('hidden');
  4917. entries.forEach((e, idx) => {
  4918. const tr = document.createElement('tr');
  4919. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4920. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4921. tr.innerHTML = `
  4922. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4923. <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>
  4924. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4925. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4926. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4927. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4928. <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>
  4929. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4930. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4931. </td>
  4932. `;
  4933. tbody.appendChild(tr);
  4934. });
  4935. populateCommonAddrListDatalist();
  4936. }
  4937. function openAddAddrListModal() {
  4938. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4939. document.getElementById('addrlist-modal-id').value = '';
  4940. document.getElementById('addrlist-modal-name').value = '';
  4941. document.getElementById('addrlist-modal-addr').value = '';
  4942. document.getElementById('addrlist-modal-comment').value = '';
  4943. document.getElementById('addrlist-modal-disabled').checked = false;
  4944. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4945. if (submitBtn) submitBtn.innerText = 'Add to List';
  4946. document.getElementById('addrlist-modal').classList.remove('hidden');
  4947. }
  4948. function openEditAddrListModal(id) {
  4949. const e = (state.addressLists || []).find(item => item.id === id);
  4950. if (!e) return;
  4951. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4952. document.getElementById('addrlist-modal-id').value = e.id;
  4953. document.getElementById('addrlist-modal-name').value = e.name;
  4954. document.getElementById('addrlist-modal-addr').value = e.address;
  4955. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4956. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4957. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4958. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4959. document.getElementById('addrlist-modal').classList.remove('hidden');
  4960. }
  4961. function closeAddrListModal() {
  4962. document.getElementById('addrlist-modal').classList.add('hidden');
  4963. }
  4964. async function submitSaveAddrList(e) {
  4965. e.preventDefault();
  4966. const id = document.getElementById('addrlist-modal-id').value;
  4967. const name = document.getElementById('addrlist-modal-name').value.trim();
  4968. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4969. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4970. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4971. try {
  4972. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4973. method: 'POST',
  4974. headers: { 'Content-Type': 'application/json' },
  4975. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4976. });
  4977. if (res.ok) {
  4978. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4979. closeAddrListModal();
  4980. loadFirewall(false);
  4981. } else {
  4982. const err = await res.json();
  4983. showToast('Error', err.message || 'Failed to save address list', 'error');
  4984. }
  4985. } catch (err) {
  4986. showToast('Error', err.message, 'error');
  4987. }
  4988. }
  4989. async function toggleAddrListState(id, disabled) {
  4990. try {
  4991. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4992. method: 'POST',
  4993. headers: { 'Content-Type': 'application/json' },
  4994. body: JSON.stringify({ disabled })
  4995. });
  4996. if (res.ok) {
  4997. loadFirewall(false);
  4998. }
  4999. } catch (err) {
  5000. showToast('Error', err.message, 'error');
  5001. }
  5002. }
  5003. async function deleteAddrList(id) {
  5004. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5005. try {
  5006. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5007. if (res.ok) {
  5008. showToast('Deleted', 'Address list item removed', 'info');
  5009. loadFirewall(false);
  5010. }
  5011. } catch (err) {
  5012. showToast('Error', err.message, 'error');
  5013. }
  5014. }
  5015. // ----------------- Geo-Location IP Management -----------------
  5016. async function loadGeoIP() {
  5017. try {
  5018. const [statusRes, countriesRes] = await Promise.all([
  5019. fetch(`${API_BASE}/firewall/geoip/status`),
  5020. fetch(`${API_BASE}/firewall/geoip/countries`)
  5021. ]);
  5022. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5023. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5024. updateGeoHeader();
  5025. renderGeoCountries();
  5026. } catch (err) {
  5027. console.error('Failed to load GeoIP:', err);
  5028. }
  5029. }
  5030. function getGeoUsageMap() {
  5031. const usage = {};
  5032. const checkRule = (r, type) => {
  5033. ['src_geoip', 'dst_geoip'].forEach(field => {
  5034. let val = (r && r[field]) || '';
  5035. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5036. if (code) {
  5037. if (!usage[code]) usage[code] = [];
  5038. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5039. if (!usage[code].includes(label)) usage[code].push(label);
  5040. }
  5041. });
  5042. };
  5043. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5044. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5045. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5046. return usage;
  5047. }
  5048. function updateGeoHeader() {
  5049. const s = state.geoStatus || {};
  5050. const statusBadge = document.getElementById('geo-status-badge');
  5051. if (statusBadge) {
  5052. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5053. statusBadge.className = s.auto_update
  5054. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5055. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5056. }
  5057. const intervalLabel = document.getElementById('geo-interval-label');
  5058. if (intervalLabel) {
  5059. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5060. }
  5061. const usageMap = getGeoUsageMap();
  5062. const inUseCount = Object.keys(usageMap).length;
  5063. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5064. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5065. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5066. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5067. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5068. if (lastSyncEl) {
  5069. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5070. const d = new Date(s.last_updated);
  5071. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5072. } else {
  5073. lastSyncEl.innerText = 'Never (Sync Pending)';
  5074. }
  5075. }
  5076. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5077. if (nextSyncEl) {
  5078. if (s.next_update && !s.next_update.startsWith('0001')) {
  5079. const d = new Date(s.next_update);
  5080. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5081. } else {
  5082. nextSyncEl.innerText = '-';
  5083. }
  5084. }
  5085. const badge = document.getElementById('fw-badge-geo');
  5086. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5087. }
  5088. function renderGeoCountries() {
  5089. const tbody = document.getElementById('geo-table-body');
  5090. const empty = document.getElementById('geo-empty');
  5091. if (!tbody) return;
  5092. tbody.innerHTML = '';
  5093. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5094. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5095. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5096. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5097. const usageMap = getGeoUsageMap();
  5098. const countries = (state.geoCountries || []).filter(c => {
  5099. const isUsed = !!usageMap[c.code];
  5100. if (inUseOnly && !isUsed) return false;
  5101. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5102. if (continent && c.continent !== continent) return false;
  5103. if (q) {
  5104. const matchCode = c.code.toLowerCase().includes(q);
  5105. const matchName = c.name.toLowerCase().includes(q);
  5106. if (!matchCode && !matchName) return false;
  5107. }
  5108. return true;
  5109. });
  5110. if (countries.length === 0) {
  5111. empty?.classList.remove('hidden');
  5112. return;
  5113. }
  5114. empty?.classList.add('hidden');
  5115. countries.forEach(c => {
  5116. const tr = document.createElement('tr');
  5117. const isUsed = !!usageMap[c.code];
  5118. const rulesUsing = usageMap[c.code] || [];
  5119. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5120. let statusHtml = '';
  5121. if (isUsed) {
  5122. 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>`;
  5123. } else if (c.subnet_count > 0) {
  5124. 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>';
  5125. } else {
  5126. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5127. }
  5128. tr.innerHTML = `
  5129. <td class="py-2.5 px-3 text-center">
  5130. <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'}">
  5131. ${c.code}
  5132. </span>
  5133. </td>
  5134. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5135. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5136. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5137. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5138. </td>
  5139. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5140. <td class="py-2.5 px-3">
  5141. ${statusHtml}
  5142. </td>
  5143. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5144. <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>
  5145. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5146. </td>
  5147. `;
  5148. tbody.appendChild(tr);
  5149. });
  5150. }
  5151. function quickFilterGeo(preset) {
  5152. const searchInput = document.getElementById('geo-search-input');
  5153. const continentSel = document.getElementById('geo-continent-filter');
  5154. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5155. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5156. if (searchInput) searchInput.value = '';
  5157. if (continentSel) continentSel.value = '';
  5158. if (inUseCheck) inUseCheck.checked = false;
  5159. if (cachedCheck) cachedCheck.checked = false;
  5160. if (preset === 'GR') {
  5161. if (searchInput) searchInput.value = 'Greece';
  5162. } else if (preset === 'Europe') {
  5163. if (continentSel) continentSel.value = 'Europe';
  5164. } else if (preset === 'HIGHRISK') {
  5165. if (searchInput) searchInput.value = 'China';
  5166. }
  5167. renderGeoCountries();
  5168. }
  5169. async function toggleGeoCountry(code, enabled) {
  5170. try {
  5171. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5172. method: 'POST',
  5173. headers: { 'Content-Type': 'application/json' },
  5174. body: JSON.stringify({ enabled })
  5175. });
  5176. if (res.ok) {
  5177. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5178. loadGeoIP();
  5179. } else {
  5180. const err = await res.json();
  5181. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5182. }
  5183. } catch (err) {
  5184. showToast('Error', err.message, 'error');
  5185. }
  5186. }
  5187. async function updateGeoCountry(code) {
  5188. try {
  5189. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5190. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5191. if (res.ok) {
  5192. const data = await res.json();
  5193. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5194. loadGeoIP();
  5195. } else {
  5196. const err = await res.json();
  5197. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5198. }
  5199. } catch (err) {
  5200. showToast('Error', err.message, 'error');
  5201. }
  5202. }
  5203. async function triggerGeoUpdateNow() {
  5204. const spinner = document.getElementById('geo-update-spinner');
  5205. if (spinner) spinner.classList.remove('hidden');
  5206. try {
  5207. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5208. if (res.ok) {
  5209. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5210. setTimeout(() => {
  5211. loadGeoIP();
  5212. if (spinner) spinner.classList.add('hidden');
  5213. }, 2500);
  5214. } else {
  5215. const err = await res.json();
  5216. showToast('Notice', err.message || 'Update in progress', 'info');
  5217. if (spinner) spinner.classList.add('hidden');
  5218. }
  5219. } catch (err) {
  5220. showToast('Error', err.message, 'error');
  5221. if (spinner) spinner.classList.add('hidden');
  5222. }
  5223. }
  5224. async function applyGeoPreset(preset) {
  5225. try {
  5226. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5227. method: 'POST',
  5228. headers: { 'Content-Type': 'application/json' },
  5229. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5230. });
  5231. if (res.ok) {
  5232. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5233. loadGeoIP();
  5234. }
  5235. } catch (err) {
  5236. showToast('Error', err.message, 'error');
  5237. }
  5238. }
  5239. function openGeoIntervalModal() {
  5240. const s = state.geoStatus || {};
  5241. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5242. const sel = document.getElementById('geo-cfg-interval');
  5243. const customBox = document.getElementById('geo-cfg-custom-box');
  5244. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5245. const curHours = s.interval_hours || 24;
  5246. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5247. if (matchOption) {
  5248. sel.value = String(curHours);
  5249. customBox.classList.add('hidden');
  5250. } else {
  5251. sel.value = 'custom';
  5252. customHoursInput.value = curHours;
  5253. customBox.classList.remove('hidden');
  5254. }
  5255. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5256. }
  5257. function closeGeoIntervalModal() {
  5258. document.getElementById('geo-interval-modal').classList.add('hidden');
  5259. }
  5260. function toggleCustomGeoInterval() {
  5261. const val = document.getElementById('geo-cfg-interval').value;
  5262. const customBox = document.getElementById('geo-cfg-custom-box');
  5263. if (val === 'custom') {
  5264. customBox.classList.remove('hidden');
  5265. } else {
  5266. customBox.classList.add('hidden');
  5267. }
  5268. }
  5269. async function submitGeoIntervalSettings(e) {
  5270. e.preventDefault();
  5271. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5272. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5273. let hours = 24;
  5274. if (intervalVal === 'custom') {
  5275. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5276. } else {
  5277. hours = parseInt(intervalVal, 10) || 24;
  5278. }
  5279. try {
  5280. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5281. method: 'POST',
  5282. headers: { 'Content-Type': 'application/json' },
  5283. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5284. });
  5285. if (res.ok) {
  5286. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5287. closeGeoIntervalModal();
  5288. loadGeoIP();
  5289. } else {
  5290. const err = await res.json();
  5291. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5292. }
  5293. } catch (err) {
  5294. showToast('Error', err.message, 'error');
  5295. }
  5296. }
  5297. async function viewGeoSubnets(code, name) {
  5298. if (!name) {
  5299. const found = (state.geoCountries || []).find(x => x.code === code);
  5300. name = found ? found.name : code;
  5301. }
  5302. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5303. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5304. const listEl = document.getElementById('geo-subnets-list');
  5305. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5306. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5307. try {
  5308. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5309. if (res.ok) {
  5310. const data = await res.json();
  5311. const subnets = data.subnets || [];
  5312. if (subnets.length === 0) {
  5313. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5314. } else {
  5315. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5316. }
  5317. } else {
  5318. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5319. }
  5320. } catch (err) {
  5321. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5322. }
  5323. }
  5324. function closeGeoSubnetsModal() {
  5325. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5326. }
  5327. // ----------------- Active Connections Tracking -----------------
  5328. async function loadConnections() {
  5329. try {
  5330. const res = await fetch(`${API_BASE}/firewall/connections`);
  5331. const data = await res.json();
  5332. state.connections = Array.isArray(data) ? data : [];
  5333. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5334. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5335. renderConnections();
  5336. } catch (err) {
  5337. console.error('Failed to load connections:', err);
  5338. }
  5339. }
  5340. function renderConnections() {
  5341. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5342. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5343. const tbody = document.getElementById('conns-table-body');
  5344. const empty = document.getElementById('conns-empty');
  5345. if (!tbody) return;
  5346. tbody.innerHTML = '';
  5347. const conns = (state.connections || []).filter(c => {
  5348. if (protoFilter && c.protocol !== protoFilter) return false;
  5349. if (search) {
  5350. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5351. if (!line.includes(search)) return false;
  5352. }
  5353. return true;
  5354. });
  5355. if (conns.length === 0) {
  5356. empty?.classList.remove('hidden');
  5357. return;
  5358. }
  5359. empty?.classList.add('hidden');
  5360. conns.slice(0, 150).forEach(c => {
  5361. const tr = document.createElement('tr');
  5362. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5363. let stateColor = 'text-slate-400';
  5364. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5365. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5366. tr.innerHTML = `
  5367. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5368. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5369. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5370. <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>
  5371. <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>
  5372. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5373. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5374. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5375. <td class="py-2.5 px-3 text-right font-sans">
  5376. <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>
  5377. </td>
  5378. `;
  5379. tbody.appendChild(tr);
  5380. });
  5381. }
  5382. async function killConnection(protocol, src, sport, dst, dport) {
  5383. try {
  5384. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5385. method: 'POST',
  5386. headers: { 'Content-Type': 'application/json' },
  5387. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5388. });
  5389. if (res.ok) {
  5390. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5391. loadConnections();
  5392. }
  5393. } catch (err) {
  5394. showToast('Error', err.message, 'error');
  5395. }
  5396. }
  5397. async function resetFirewallCounters() {
  5398. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5399. try {
  5400. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5401. if (res.ok) {
  5402. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5403. loadFirewall(false);
  5404. }
  5405. } catch (err) {
  5406. showToast('Error', err.message, 'error');
  5407. }
  5408. }
  5409. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5410. function switchRoutesSubTab(tab) {
  5411. state.routesSubTab = tab;
  5412. const tabs = ['routes', 'rules', 'tables'];
  5413. tabs.forEach(t => {
  5414. const panel = document.getElementById(`routes-subtab-${t}`);
  5415. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5416. if (panel) {
  5417. if (t === tab) panel.classList.remove('hidden');
  5418. else panel.classList.add('hidden');
  5419. }
  5420. if (btn) {
  5421. if (t === tab) {
  5422. 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';
  5423. } else {
  5424. 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';
  5425. }
  5426. }
  5427. });
  5428. setTimeout(initTableSorting, 50);
  5429. }
  5430. async function loadRoutes() {
  5431. try {
  5432. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5433. fetch(`${API_BASE}/routes`),
  5434. fetch(`${API_BASE}/routing/rules`),
  5435. fetch(`${API_BASE}/routing/tables`)
  5436. ]);
  5437. if (routesRes.ok) state.routes = await routesRes.json();
  5438. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5439. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5440. const bRoutes = document.getElementById('routes-badge-routes');
  5441. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5442. const showSystem = document.getElementById('prule-show-system')?.checked;
  5443. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5444. const bRules = document.getElementById('routes-badge-rules');
  5445. if (bRules) bRules.innerText = userRules.length;
  5446. const bTables = document.getElementById('routes-badge-tables');
  5447. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5448. const bRoutesCount = document.getElementById('badge-routes-count');
  5449. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5450. renderRoutesList();
  5451. renderPolicyRules();
  5452. renderRoutingTables();
  5453. } catch (err) {
  5454. console.error('Failed to load routing:', err);
  5455. }
  5456. }
  5457. function renderRoutesList() {
  5458. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5459. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5460. const tbody = document.getElementById('routes-table-body');
  5461. const empty = document.getElementById('routes-empty');
  5462. if (!tbody) return;
  5463. tbody.innerHTML = '';
  5464. // Update table filter select
  5465. const sel = document.getElementById('routes-filter-table');
  5466. if (sel) {
  5467. const cur = sel.value;
  5468. sel.innerHTML = '<option value="">All Tables</option>';
  5469. (state.routingTables || []).forEach(t => {
  5470. const opt = document.createElement('option');
  5471. opt.value = t.name;
  5472. opt.innerText = t.name;
  5473. if (t.name === cur) opt.selected = true;
  5474. sel.appendChild(opt);
  5475. });
  5476. }
  5477. const routes = (state.routes || []).filter(r => {
  5478. if (tableFilter && r.routing_table !== tableFilter) return false;
  5479. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5480. if (typeFilter === 'multicast' && !r.multicast) return false;
  5481. if (typeFilter === 'static' && !r.static) return false;
  5482. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5483. if (typeFilter === 'connected' && !r.connect) return false;
  5484. return true;
  5485. });
  5486. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5487. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5488. let summaryText = `${routes.length} Routes`;
  5489. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5490. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5491. const badgeEl = document.getElementById('routes-count-badge');
  5492. if (badgeEl) badgeEl.innerText = summaryText;
  5493. if (routes.length === 0) {
  5494. empty?.classList.remove('hidden');
  5495. return;
  5496. }
  5497. empty?.classList.add('hidden');
  5498. routes.forEach(r => {
  5499. const tr = document.createElement('tr');
  5500. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5501. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5502. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5503. let flags = '';
  5504. if (r.dynamic) flags += 'D';
  5505. if (r.active) flags += 'A';
  5506. if (r.connect) flags += 'C';
  5507. if (r.static) flags += 'S';
  5508. if (r.ecmp) flags += 'E';
  5509. if (r.multicast) flags += 'M';
  5510. if (r.disabled) flags += 'X';
  5511. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5512. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5513. if (r.check_gateway === 'internet') {
  5514. if (r.health_status === 'online') {
  5515. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5516. healthCell = `
  5517. <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)">
  5518. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5519. <span>Internet OK (${ms}ms)</span>
  5520. </span>
  5521. `;
  5522. } else if (r.health_status === 'offline') {
  5523. healthCell = `
  5524. <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.">
  5525. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5526. <span>Internet Down</span>
  5527. </span>
  5528. `;
  5529. } else {
  5530. healthCell = `
  5531. <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">
  5532. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  5533. <span>Checking...</span>
  5534. </span>
  5535. `;
  5536. }
  5537. } else if (r.check_gateway === 'ping') {
  5538. if (r.health_status === 'online') {
  5539. healthCell = `
  5540. <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">
  5541. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  5542. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  5543. </span>
  5544. `;
  5545. } else if (r.health_status === 'offline') {
  5546. healthCell = `
  5547. <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">
  5548. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5549. <span>Gateway Dead</span>
  5550. </span>
  5551. `;
  5552. }
  5553. }
  5554. const flagDescriptions = [];
  5555. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  5556. if (r.active) flagDescriptions.push('Active (A)');
  5557. if (r.connect) flagDescriptions.push('Connected (C)');
  5558. if (r.static) flagDescriptions.push('Static (S)');
  5559. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  5560. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  5561. if (r.disabled) flagDescriptions.push('Disabled (X)');
  5562. tr.innerHTML = `
  5563. <td class="py-2.5 px-3 text-center">
  5564. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  5565. 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')
  5566. }" title="Flags: ${flagDescriptions.join(', ')}">
  5567. ${flags || '-'}
  5568. </span>
  5569. </td>
  5570. <td class="py-2.5 px-3">
  5571. <div class="flex items-center gap-1.5 flex-wrap">
  5572. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  5573. ${r.ecmp ? `
  5574. <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)">
  5575. <span>⚡ ECMP</span>
  5576. </span>
  5577. ` : ''}
  5578. ${r.multicast ? `
  5579. <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">
  5580. <span>IGMP</span>
  5581. </span>
  5582. ` : ''}
  5583. </div>
  5584. </td>
  5585. <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>
  5586. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5587. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5588. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5589. <td class="py-2.5 px-3">${healthCell}</td>
  5590. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5591. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5592. ${r.static ? `
  5593. <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>
  5594. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5595. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5596. ` : `
  5597. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5598. `}
  5599. </td>
  5600. `;
  5601. tbody.appendChild(tr);
  5602. });
  5603. }
  5604. function openAddRouteModal() {
  5605. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5606. document.getElementById('route-modal-id').value = '';
  5607. document.getElementById('route-modal-old-dst').value = '';
  5608. document.getElementById('route-modal-old-gw').value = '';
  5609. document.getElementById('route-modal-old-distance').value = '';
  5610. document.getElementById('route-modal-old-table').value = '';
  5611. document.getElementById('route-modal-old-iface').value = '';
  5612. const dstInput = document.getElementById('route-modal-dst');
  5613. const gwInput = document.getElementById('route-modal-gw');
  5614. const distInput = document.getElementById('route-modal-distance');
  5615. const ifaceSelect = document.getElementById('route-modal-iface');
  5616. const tableSelect = document.getElementById('route-modal-table');
  5617. const commentInput = document.getElementById('route-modal-comment');
  5618. const disCheck = document.getElementById('route-modal-disabled');
  5619. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5620. dstInput.disabled = false;
  5621. dstInput.value = '0.0.0.0/0';
  5622. gwInput.disabled = false;
  5623. gwInput.value = '';
  5624. distInput.disabled = false;
  5625. distInput.value = '1';
  5626. ifaceSelect.disabled = false;
  5627. tableSelect.disabled = false;
  5628. commentInput.disabled = false;
  5629. commentInput.value = '';
  5630. disCheck.disabled = false;
  5631. disCheck.checked = false;
  5632. if (saveBtn) saveBtn.classList.remove('hidden');
  5633. const checkGw = document.getElementById('route-modal-check-gw');
  5634. if (checkGw) checkGw.value = 'internet';
  5635. const checkTarget = document.getElementById('route-modal-check-target');
  5636. if (checkTarget) checkTarget.value = '1.1.1.1';
  5637. const checkInterval = document.getElementById('route-modal-check-interval');
  5638. if (checkInterval) checkInterval.value = '5';
  5639. const checkThresh = document.getElementById('route-modal-check-threshold');
  5640. if (checkThresh) checkThresh.value = '3';
  5641. toggleRouteCheckModeUI();
  5642. populateInterfaceSelect('route-modal-iface');
  5643. // Populate tables
  5644. tableSelect.innerHTML = '';
  5645. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5646. const opt = document.createElement('option');
  5647. opt.value = t.name;
  5648. opt.innerText = t.name;
  5649. if (t.name === 'main') opt.selected = true;
  5650. tableSelect.appendChild(opt);
  5651. });
  5652. document.getElementById('route-modal').classList.remove('hidden');
  5653. }
  5654. function openEditRouteModal(id) {
  5655. const r = (state.routes || []).find(route => route.id === id);
  5656. if (!r) return;
  5657. const isStatic = !!r.static;
  5658. document.getElementById('route-modal-title').innerText = isStatic
  5659. ? `Edit Route: ${r.dst_address}`
  5660. : `Route Properties (Read Only): ${r.dst_address}`;
  5661. document.getElementById('route-modal-id').value = r.id;
  5662. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5663. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5664. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5665. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5666. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5667. const dstInput = document.getElementById('route-modal-dst');
  5668. const gwInput = document.getElementById('route-modal-gw');
  5669. const distInput = document.getElementById('route-modal-distance');
  5670. const ifaceSelect = document.getElementById('route-modal-iface');
  5671. const tableSelect = document.getElementById('route-modal-table');
  5672. const commentInput = document.getElementById('route-modal-comment');
  5673. const disCheck = document.getElementById('route-modal-disabled');
  5674. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5675. dstInput.value = r.dst_address;
  5676. gwInput.value = r.gateway || '';
  5677. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5678. commentInput.value = r.comment || '';
  5679. disCheck.checked = !!r.disabled;
  5680. const checkGw = document.getElementById('route-modal-check-gw');
  5681. if (checkGw) checkGw.value = r.check_gateway || 'none';
  5682. const checkTarget = document.getElementById('route-modal-check-target');
  5683. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  5684. const checkInterval = document.getElementById('route-modal-check-interval');
  5685. if (checkInterval) checkInterval.value = r.check_interval || 5;
  5686. const checkThresh = document.getElementById('route-modal-check-threshold');
  5687. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  5688. toggleRouteCheckModeUI();
  5689. dstInput.disabled = !isStatic;
  5690. gwInput.disabled = !isStatic;
  5691. distInput.disabled = !isStatic;
  5692. ifaceSelect.disabled = !isStatic;
  5693. tableSelect.disabled = !isStatic;
  5694. commentInput.disabled = !isStatic;
  5695. disCheck.disabled = !isStatic;
  5696. if (checkGw) checkGw.disabled = !isStatic;
  5697. if (checkTarget) checkTarget.disabled = !isStatic;
  5698. if (checkInterval) checkInterval.disabled = !isStatic;
  5699. if (checkThresh) checkThresh.disabled = !isStatic;
  5700. if (saveBtn) {
  5701. if (isStatic) {
  5702. saveBtn.classList.remove('hidden');
  5703. } else {
  5704. saveBtn.classList.add('hidden');
  5705. }
  5706. }
  5707. populateInterfaceSelect('route-modal-iface', r.interface);
  5708. tableSelect.innerHTML = '';
  5709. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5710. const opt = document.createElement('option');
  5711. opt.value = t.name;
  5712. opt.innerText = t.name;
  5713. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5714. tableSelect.appendChild(opt);
  5715. });
  5716. document.getElementById('route-modal').classList.remove('hidden');
  5717. }
  5718. function closeRouteModal() {
  5719. document.getElementById('route-modal').classList.add('hidden');
  5720. }
  5721. function setRouteCheckTarget(ip) {
  5722. const inp = document.getElementById('route-modal-check-target');
  5723. if (inp) inp.value = ip;
  5724. }
  5725. function toggleRouteCheckModeUI() {
  5726. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  5727. const targetRow = document.getElementById('route-row-check-target');
  5728. const paramsRow = document.getElementById('route-row-check-params');
  5729. if (mode === 'none') {
  5730. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5731. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  5732. } else if (mode === 'ping') {
  5733. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5734. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5735. } else { // internet
  5736. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  5737. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5738. }
  5739. }
  5740. async function submitSaveRoute(e) {
  5741. e.preventDefault();
  5742. const id = document.getElementById('route-modal-id').value;
  5743. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5744. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5745. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5746. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5747. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5748. const dst = document.getElementById('route-modal-dst').value.trim();
  5749. const gw = document.getElementById('route-modal-gw').value.trim();
  5750. const table = document.getElementById('route-modal-table').value;
  5751. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5752. const iface = document.getElementById('route-modal-iface').value;
  5753. const comment = document.getElementById('route-modal-comment').value.trim();
  5754. const disabled = document.getElementById('route-modal-disabled').checked;
  5755. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  5756. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  5757. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  5758. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  5759. if (!dst) {
  5760. showToast('Error', 'Destination address is required', 'error');
  5761. return;
  5762. }
  5763. if (!gw && !iface) {
  5764. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5765. return;
  5766. }
  5767. const payload = {
  5768. id,
  5769. old_dst_address: oldDst,
  5770. old_gateway: oldGw,
  5771. old_routing_table: oldTable,
  5772. old_interface: oldIface,
  5773. dst_address: dst,
  5774. gateway: gw || iface,
  5775. routing_table: table,
  5776. distance,
  5777. interface: iface,
  5778. comment,
  5779. disabled,
  5780. check_gateway,
  5781. check_target,
  5782. check_interval,
  5783. check_threshold
  5784. };
  5785. if (oldDistStr !== undefined && oldDistStr !== '') {
  5786. payload.old_distance = parseInt(oldDistStr, 10);
  5787. }
  5788. try {
  5789. const res = await fetch(`${API_BASE}/routes`, {
  5790. method: 'POST',
  5791. headers: { 'Content-Type': 'application/json' },
  5792. body: JSON.stringify(payload)
  5793. });
  5794. if (res.ok) {
  5795. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5796. closeRouteModal();
  5797. loadRoutes();
  5798. } else {
  5799. const err = await res.json();
  5800. showToast('Error', err.message || 'Failed to save route', 'error');
  5801. }
  5802. } catch (err) {
  5803. showToast('Error', err.message, 'error');
  5804. }
  5805. }
  5806. async function toggleRouteState(id, disabled) {
  5807. try {
  5808. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5809. method: 'POST',
  5810. headers: { 'Content-Type': 'application/json' },
  5811. body: JSON.stringify({ disabled })
  5812. });
  5813. if (res.ok) loadRoutes();
  5814. } catch (err) {
  5815. showToast('Error', err.message, 'error');
  5816. }
  5817. }
  5818. async function deleteRoute(id) {
  5819. if (!confirm('Are you sure you want to delete this route?')) return;
  5820. try {
  5821. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5822. if (res.ok) {
  5823. showToast('Deleted', 'Route removed', 'success');
  5824. loadRoutes();
  5825. }
  5826. } catch (err) {
  5827. showToast('Error', err.message, 'error');
  5828. }
  5829. }
  5830. // ----------------- Policy Rules (/ip route rule) -----------------
  5831. function renderPolicyRules() {
  5832. const tbody = document.getElementById('rules-table-body');
  5833. const empty = document.getElementById('rules-empty');
  5834. if (!tbody) return;
  5835. tbody.innerHTML = '';
  5836. const showSystem = document.getElementById('prule-show-system')?.checked;
  5837. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5838. const countBadge = document.getElementById('rules-count-badge');
  5839. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5840. const bRules = document.getElementById('routes-badge-rules');
  5841. if (bRules) bRules.innerText = filtered.length;
  5842. if (filtered.length === 0) {
  5843. empty?.classList.remove('hidden');
  5844. return;
  5845. }
  5846. empty?.classList.add('hidden');
  5847. filtered.forEach(pr => {
  5848. const isSys = pr.is_default || pr.is_system;
  5849. const tr = document.createElement('tr');
  5850. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5851. tr.innerHTML = `
  5852. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5853. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5854. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5855. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5856. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5857. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5858. <td class="py-2.5 px-3 text-right font-sans">
  5859. ${!pr.is_default ? `
  5860. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5861. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5862. </td>
  5863. `;
  5864. tbody.appendChild(tr);
  5865. });
  5866. }
  5867. function openAddPolicyRuleModal() {
  5868. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5869. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5870. document.getElementById('prule-modal-mark').value = '';
  5871. document.getElementById('prule-modal-src').value = '';
  5872. document.getElementById('prule-modal-dst').value = '';
  5873. const sel = document.getElementById('prule-modal-table');
  5874. sel.innerHTML = '';
  5875. (state.routingTables || []).forEach(t => {
  5876. const opt = document.createElement('option');
  5877. opt.value = t.name;
  5878. opt.innerText = t.name;
  5879. sel.appendChild(opt);
  5880. });
  5881. document.getElementById('prule-modal').classList.remove('hidden');
  5882. }
  5883. function closePolicyRuleModal() {
  5884. document.getElementById('prule-modal').classList.add('hidden');
  5885. }
  5886. async function submitSavePolicyRule(e) {
  5887. e.preventDefault();
  5888. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5889. const mark = document.getElementById('prule-modal-mark').value.trim();
  5890. const src = document.getElementById('prule-modal-src').value.trim();
  5891. const dst = document.getElementById('prule-modal-dst').value.trim();
  5892. const table = document.getElementById('prule-modal-table').value;
  5893. const action = document.getElementById('prule-modal-action').value;
  5894. try {
  5895. const res = await fetch(`${API_BASE}/routing/rules`, {
  5896. method: 'POST',
  5897. headers: { 'Content-Type': 'application/json' },
  5898. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5899. });
  5900. if (res.ok) {
  5901. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5902. closePolicyRuleModal();
  5903. loadRoutes();
  5904. } else {
  5905. const err = await res.json();
  5906. showToast('Error', err.message, 'error');
  5907. }
  5908. } catch (err) {
  5909. showToast('Error', err.message, 'error');
  5910. }
  5911. }
  5912. async function deletePolicyRule(id) {
  5913. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5914. try {
  5915. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5916. if (res.ok) {
  5917. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5918. loadRoutes();
  5919. }
  5920. } catch (err) {
  5921. showToast('Error', err.message, 'error');
  5922. }
  5923. }
  5924. // ----------------- Routing Tables -----------------
  5925. function renderRoutingTables() {
  5926. const tbody = document.getElementById('tables-table-body');
  5927. if (!tbody) return;
  5928. tbody.innerHTML = '';
  5929. (state.routingTables || []).forEach(t => {
  5930. const tr = document.createElement('tr');
  5931. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5932. tr.innerHTML = `
  5933. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5934. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5935. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5936. `;
  5937. tbody.appendChild(tr);
  5938. });
  5939. }
  5940. function openAddTableModal() {
  5941. document.getElementById('table-modal-name').value = '';
  5942. document.getElementById('table-modal-id').value = '';
  5943. document.getElementById('table-modal-comment').value = '';
  5944. document.getElementById('table-modal').classList.remove('hidden');
  5945. }
  5946. function closeTableModal() {
  5947. document.getElementById('table-modal').classList.add('hidden');
  5948. }
  5949. async function submitSaveTable(e) {
  5950. e.preventDefault();
  5951. const name = document.getElementById('table-modal-name').value.trim();
  5952. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5953. const comment = document.getElementById('table-modal-comment').value.trim();
  5954. try {
  5955. const res = await fetch(`${API_BASE}/routing/tables`, {
  5956. method: 'POST',
  5957. headers: { 'Content-Type': 'application/json' },
  5958. body: JSON.stringify({ name, table_id: id, comment })
  5959. });
  5960. if (res.ok) {
  5961. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5962. closeTableModal();
  5963. loadRoutes();
  5964. } else {
  5965. const err = await res.json();
  5966. showToast('Error', err.message, 'error');
  5967. }
  5968. } catch (err) {
  5969. showToast('Error', err.message, 'error');
  5970. }
  5971. }
  5972. async function loadDebianConfig() {
  5973. const view = document.getElementById('debian-config-view');
  5974. view.innerText = 'Generating live configuration...';
  5975. try {
  5976. const res = await fetch(`${API_BASE}/debian/config`);
  5977. const data = await res.json();
  5978. view.innerText = data.content || '# Empty config';
  5979. } catch (err) {
  5980. view.innerText = 'Failed to generate Debian network config.';
  5981. }
  5982. }
  5983. async function saveDebianConfig() {
  5984. try {
  5985. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5986. const data = await res.json();
  5987. if (res.ok) {
  5988. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5989. loadDebianConfig();
  5990. }
  5991. } catch (err) {
  5992. showToast('Error', err.message, 'error');
  5993. }
  5994. }
  5995. function showToast(title, message, type = 'info') {
  5996. const container = document.getElementById('toast-container');
  5997. const toast = document.createElement('div');
  5998. const borderColors = {
  5999. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6000. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6001. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6002. };
  6003. 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}`;
  6004. toast.innerHTML = `
  6005. <div class="flex-1">
  6006. <div class="font-bold text-xs text-white">${title}</div>
  6007. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6008. </div>
  6009. `;
  6010. container.appendChild(toast);
  6011. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6012. setTimeout(() => {
  6013. toast.classList.add('opacity-0', 'translate-y-2');
  6014. setTimeout(() => toast.remove(), 300);
  6015. }, 4000);
  6016. }
  6017. function formatTraffic(bytesPerSec) {
  6018. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6019. const kb = bytesPerSec / 1024;
  6020. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6021. const mb = kb / 1024;
  6022. return `${mb.toFixed(2)} MB/s`;
  6023. }
  6024. function toggleSidebar() {
  6025. const sb = document.getElementById('sidebar');
  6026. sb.classList.toggle('-translate-x-full');
  6027. }
  6028. // ======================== EoIP (Ethernet over IP) ========================
  6029. async function loadEoIP(populate = true) {
  6030. try {
  6031. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6032. const data = await res.json();
  6033. state.eoipTunnels = Array.isArray(data) ? data : [];
  6034. const badge = document.getElementById('eoip-count-badge');
  6035. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6036. const sideBadge = document.getElementById('badge-eoip-count');
  6037. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6038. renderEoIPTunnels();
  6039. } catch (err) {
  6040. console.error('Failed to load EoIP:', err);
  6041. }
  6042. }
  6043. function renderEoIPTunnels() {
  6044. const tbody = document.getElementById('eoip-table-body');
  6045. const empty = document.getElementById('eoip-empty');
  6046. if (!tbody) return;
  6047. tbody.innerHTML = '';
  6048. const tunnels = state.eoipTunnels || [];
  6049. if (tunnels.length === 0) {
  6050. empty?.classList.remove('hidden');
  6051. return;
  6052. }
  6053. empty?.classList.add('hidden');
  6054. tunnels.forEach(t => {
  6055. const tr = document.createElement('tr');
  6056. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6057. tr.innerHTML = `
  6058. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6059. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6060. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6061. <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>
  6062. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6063. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6064. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6065. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6066. <td class="py-2.5 px-3 font-mono text-[11px]">
  6067. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6068. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6069. </td>
  6070. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6071. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6072. <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>
  6073. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6074. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6075. </td>
  6076. `;
  6077. tbody.appendChild(tr);
  6078. });
  6079. }
  6080. function openAddEoIPModal() {
  6081. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6082. document.getElementById('eoip-modal-id').value = '';
  6083. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6084. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6085. document.getElementById('eoip-modal-remote').value = '';
  6086. document.getElementById('eoip-modal-ip').value = '';
  6087. document.getElementById('eoip-modal-local').value = '';
  6088. document.getElementById('eoip-modal-mac').value = '';
  6089. document.getElementById('eoip-modal-mtu').value = '1500';
  6090. document.getElementById('eoip-modal-comment').value = '';
  6091. document.getElementById('eoip-modal-clampmss').checked = true;
  6092. document.getElementById('eoip-modal-disabled').checked = false;
  6093. document.getElementById('eoip-modal').classList.remove('hidden');
  6094. }
  6095. function openEditEoIPModal(id) {
  6096. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6097. if (!t) return;
  6098. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6099. document.getElementById('eoip-modal-id').value = t.id;
  6100. document.getElementById('eoip-modal-name').value = t.name;
  6101. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6102. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6103. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6104. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6105. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6106. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6107. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6108. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6109. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6110. document.getElementById('eoip-modal').classList.remove('hidden');
  6111. }
  6112. function closeEoIPModal() {
  6113. document.getElementById('eoip-modal').classList.add('hidden');
  6114. }
  6115. async function submitSaveEoIP(e) {
  6116. e.preventDefault();
  6117. const id = document.getElementById('eoip-modal-id').value;
  6118. const name = document.getElementById('eoip-modal-name').value.trim();
  6119. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6120. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6121. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6122. const local = document.getElementById('eoip-modal-local').value.trim();
  6123. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6124. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6125. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6126. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6127. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6128. try {
  6129. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6130. method: 'POST',
  6131. headers: { 'Content-Type': 'application/json' },
  6132. body: JSON.stringify({
  6133. id,
  6134. name,
  6135. tunnel_id: tunnelId,
  6136. remote_address: remote,
  6137. ip_address: ipAddress,
  6138. local_address: local,
  6139. mac_address: mac,
  6140. mtu,
  6141. clamp_mss: clampMss,
  6142. comment,
  6143. disabled
  6144. })
  6145. });
  6146. if (res.ok) {
  6147. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6148. closeEoIPModal();
  6149. loadEoIP(false);
  6150. fetchData(false);
  6151. } else {
  6152. const err = await res.json();
  6153. showToast('Error', err.message, 'error');
  6154. }
  6155. } catch (err) {
  6156. showToast('Error', err.message, 'error');
  6157. }
  6158. }
  6159. async function toggleEoIPState(id, disabled) {
  6160. try {
  6161. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6162. method: 'POST',
  6163. headers: { 'Content-Type': 'application/json' },
  6164. body: JSON.stringify({ disabled })
  6165. });
  6166. if (res.ok) {
  6167. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6168. loadEoIP(false);
  6169. fetchData(false);
  6170. }
  6171. } catch (err) {
  6172. showToast('Error', err.message, 'error');
  6173. }
  6174. }
  6175. async function deleteEoIP(id) {
  6176. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6177. try {
  6178. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6179. if (res.ok) {
  6180. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6181. loadEoIP(false);
  6182. fetchData(false);
  6183. }
  6184. } catch (err) {
  6185. showToast('Error', err.message, 'error');
  6186. }
  6187. }
  6188. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6189. async function loadAeroTUN(populate = true) {
  6190. try {
  6191. const [tunnelsRes, statsRes] = await Promise.all([
  6192. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6193. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6194. ]);
  6195. if (tunnelsRes.ok) {
  6196. const data = await tunnelsRes.json();
  6197. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6198. }
  6199. if (statsRes.ok) {
  6200. state.aerotunStats = await statsRes.json();
  6201. }
  6202. const countBadge = document.getElementById('aerotun-count-badge');
  6203. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6204. const sideBadge = document.getElementById('badge-aerotun-count');
  6205. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6206. renderAeroTUN();
  6207. } catch (err) {
  6208. console.error('Failed to load AeroTUN:', err);
  6209. }
  6210. }
  6211. function renderAeroTUN() {
  6212. const tbody = document.getElementById('aerotun-table-body');
  6213. const empty = document.getElementById('aerotun-empty');
  6214. // Update summary cards
  6215. const stats = state.aerotunStats || {};
  6216. const tunnels = state.aerotunTunnels || [];
  6217. const statActive = document.getElementById('aerotun-stat-active');
  6218. if (statActive) {
  6219. const activeCount = tunnels.filter(t => t.running).length;
  6220. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6221. }
  6222. const statSaved = document.getElementById('aerotun-stat-saved');
  6223. if (statSaved) {
  6224. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6225. }
  6226. const statRatio = document.getElementById('aerotun-stat-ratio');
  6227. if (statRatio) {
  6228. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6229. }
  6230. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6231. if (statTraffic) {
  6232. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6233. }
  6234. if (!tbody) return;
  6235. tbody.innerHTML = '';
  6236. if (tunnels.length === 0) {
  6237. empty?.classList.remove('hidden');
  6238. return;
  6239. }
  6240. empty?.classList.add('hidden');
  6241. tunnels.forEach(t => {
  6242. const tr = document.createElement('tr');
  6243. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6244. const modeBadge = t.mode === 'server'
  6245. ? `<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>`
  6246. : `<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>`;
  6247. const endpointInfo = t.mode === 'server'
  6248. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6249. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6250. const compBadge = t.compression
  6251. ? `<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>`
  6252. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6253. const activePeer = t.active_peer_endpoint
  6254. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6255. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6256. const rawRx = formatBytes(t.rx_bytes || 0);
  6257. const rawTx = formatBytes(t.tx_bytes || 0);
  6258. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6259. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6260. tr.innerHTML = `
  6261. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6262. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6263. <span>${escapeHtml(t.name)}</span>
  6264. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6265. </td>
  6266. <td class="py-2.5 px-3">${modeBadge}</td>
  6267. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6268. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6269. <td class="py-2.5 px-3">${compBadge}</td>
  6270. <td class="py-2.5 px-3">${activePeer}</td>
  6271. <td class="py-2.5 px-3 font-mono text-[11px]">
  6272. <span class="text-emerald-400">↓ ${rawRx}</span>
  6273. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6274. </td>
  6275. <td class="py-2.5 px-3 font-mono text-[11px]">
  6276. <span class="text-slate-400">↓ ${wireRx}</span>
  6277. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6278. </td>
  6279. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6280. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6281. ${t.running
  6282. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6283. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6284. }
  6285. <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>
  6286. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6287. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6288. </td>
  6289. `;
  6290. tbody.appendChild(tr);
  6291. });
  6292. }
  6293. function onAeroTUNModeChange() {
  6294. const mode = document.getElementById('aerotun-modal-mode').value;
  6295. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6296. const portInput = document.getElementById('aerotun-modal-port');
  6297. if (mode === 'server') {
  6298. if (!portInput.value) portInput.value = '51830';
  6299. endpointInput.placeholder = 'Optional / learned roaming peer';
  6300. } else {
  6301. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6302. if (!portInput.value) portInput.value = '';
  6303. }
  6304. }
  6305. async function generateAeroTUNKey() {
  6306. try {
  6307. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6308. if (res.ok) {
  6309. const data = await res.json();
  6310. document.getElementById('aerotun-modal-psk').value = data.key;
  6311. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6312. }
  6313. } catch (err) {
  6314. const arr = new Uint8Array(32);
  6315. crypto.getRandomValues(arr);
  6316. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6317. document.getElementById('aerotun-modal-psk').value = hex;
  6318. }
  6319. }
  6320. function openAddAeroTUNModal() {
  6321. const tunnels = state.aerotunTunnels || [];
  6322. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6323. document.getElementById('aerotun-modal-id').value = '';
  6324. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6325. document.getElementById('aerotun-modal-mode').value = 'server';
  6326. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6327. document.getElementById('aerotun-modal-endpoint').value = '';
  6328. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6329. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6330. document.getElementById('aerotun-modal-psk').value = '';
  6331. document.getElementById('aerotun-modal-mtu').value = '1420';
  6332. document.getElementById('aerotun-modal-comment').value = '';
  6333. document.getElementById('aerotun-modal-compression').checked = true;
  6334. document.getElementById('aerotun-modal-defroute').checked = false;
  6335. document.getElementById('aerotun-modal-disabled').checked = false;
  6336. generateAeroTUNKey();
  6337. onAeroTUNModeChange();
  6338. document.getElementById('aerotun-modal').classList.remove('hidden');
  6339. }
  6340. function openEditAeroTUNModal(id) {
  6341. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6342. if (!t) return;
  6343. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6344. document.getElementById('aerotun-modal-id').value = t.id;
  6345. document.getElementById('aerotun-modal-name').value = t.name;
  6346. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6347. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6348. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6349. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6350. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6351. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6352. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6353. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6354. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6355. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6356. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6357. onAeroTUNModeChange();
  6358. document.getElementById('aerotun-modal').classList.remove('hidden');
  6359. }
  6360. function closeAeroTUNModal() {
  6361. document.getElementById('aerotun-modal').classList.add('hidden');
  6362. }
  6363. async function submitSaveAeroTUN(e) {
  6364. e.preventDefault();
  6365. const id = document.getElementById('aerotun-modal-id').value;
  6366. const name = document.getElementById('aerotun-modal-name').value.trim();
  6367. const mode = document.getElementById('aerotun-modal-mode').value;
  6368. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6369. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6370. const local = document.getElementById('aerotun-modal-local').value.trim();
  6371. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6372. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6373. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6374. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6375. const compression = document.getElementById('aerotun-modal-compression').checked;
  6376. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6377. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6378. if (mode === 'client' && !endpoint) {
  6379. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6380. return;
  6381. }
  6382. if (!psk) {
  6383. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6384. return;
  6385. }
  6386. try {
  6387. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6388. method: 'POST',
  6389. headers: { 'Content-Type': 'application/json' },
  6390. body: JSON.stringify({
  6391. id,
  6392. name,
  6393. mode,
  6394. listen_port: port,
  6395. remote_endpoint: endpoint,
  6396. local_address: local,
  6397. peer_address: peer,
  6398. psk,
  6399. mtu,
  6400. compression,
  6401. default_route: defaultRoute,
  6402. comment,
  6403. disabled
  6404. })
  6405. });
  6406. if (res.ok) {
  6407. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6408. closeAeroTUNModal();
  6409. loadAeroTUN(false);
  6410. fetchData(false);
  6411. } else {
  6412. const err = await res.text();
  6413. showToast('Error Saving Tunnel', err, 'error');
  6414. }
  6415. } catch (err) {
  6416. showToast('Network Error', err.message, 'error');
  6417. }
  6418. }
  6419. async function startAeroTUNTunnel(id) {
  6420. try {
  6421. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6422. if (res.ok) {
  6423. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6424. loadAeroTUN(false);
  6425. fetchData(false);
  6426. } else {
  6427. const err = await res.text();
  6428. showToast('Failed to Start', err, 'error');
  6429. }
  6430. } catch (err) {
  6431. showToast('Error', err.message, 'error');
  6432. }
  6433. }
  6434. async function stopAeroTUNTunnel(id) {
  6435. try {
  6436. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6437. if (res.ok) {
  6438. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6439. loadAeroTUN(false);
  6440. fetchData(false);
  6441. } else {
  6442. const err = await res.text();
  6443. showToast('Failed to Stop', err, 'error');
  6444. }
  6445. } catch (err) {
  6446. showToast('Error', err.message, 'error');
  6447. }
  6448. }
  6449. async function toggleAeroTUNState(id, disabled) {
  6450. try {
  6451. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6452. method: 'POST',
  6453. headers: { 'Content-Type': 'application/json' },
  6454. body: JSON.stringify({ disabled })
  6455. });
  6456. if (res.ok) {
  6457. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6458. loadAeroTUN(false);
  6459. fetchData(false);
  6460. }
  6461. } catch (err) {
  6462. showToast('Error', err.message, 'error');
  6463. }
  6464. }
  6465. async function deleteAeroTUN(id) {
  6466. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6467. try {
  6468. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6469. if (res.ok) {
  6470. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6471. loadAeroTUN(false);
  6472. fetchData(false);
  6473. }
  6474. } catch (err) {
  6475. showToast('Error', err.message, 'error');
  6476. }
  6477. }
  6478. // ======================== PPP Central Hub & Servers ========================
  6479. function switchPPPSubTab(tab) {
  6480. state.pppSubTab = tab;
  6481. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6482. tabs.forEach(t => {
  6483. const panel = document.getElementById(`ppp-subtab-${t}`);
  6484. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6485. if (panel) {
  6486. if (t === tab) panel.classList.remove('hidden');
  6487. else panel.classList.add('hidden');
  6488. }
  6489. if (btn) {
  6490. if (t === tab) {
  6491. 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';
  6492. } else {
  6493. 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';
  6494. }
  6495. }
  6496. });
  6497. const addBtn = document.getElementById('ppp-primary-add-btn');
  6498. if (addBtn) {
  6499. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6500. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6501. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6502. else addBtn.innerHTML = '<span>Save Config</span>';
  6503. }
  6504. if (tab === 'active') loadPPPSessions();
  6505. }
  6506. function openCurrentPPPModal() {
  6507. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6508. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6509. else if (state.pppSubTab === 'active') loadPPPSessions();
  6510. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6511. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6512. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6513. }
  6514. async function loadPPP(populateDropdowns = true) {
  6515. await Promise.all([
  6516. loadPPPSecrets(),
  6517. loadPPPProfiles(),
  6518. loadPPPServers(),
  6519. loadPPPSessions()
  6520. ]);
  6521. }
  6522. async function loadPPPSecrets() {
  6523. try {
  6524. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6525. const data = await res.json();
  6526. state.pppSecrets = Array.isArray(data) ? data : [];
  6527. const b = document.getElementById('ppp-badge-secrets');
  6528. if (b) b.innerText = state.pppSecrets.length;
  6529. const b2 = document.getElementById('secrets-count-badge');
  6530. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6531. renderPPPSecrets();
  6532. } catch (err) {
  6533. console.error('Failed to load PPP secrets:', err);
  6534. }
  6535. }
  6536. function renderPPPSecrets() {
  6537. const tbody = document.getElementById('secrets-table-body');
  6538. const empty = document.getElementById('secrets-empty');
  6539. if (!tbody) return;
  6540. tbody.innerHTML = '';
  6541. const secrets = state.pppSecrets || [];
  6542. if (secrets.length === 0) {
  6543. empty?.classList.remove('hidden');
  6544. return;
  6545. }
  6546. empty?.classList.add('hidden');
  6547. secrets.forEach(s => {
  6548. const tr = document.createElement('tr');
  6549. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6550. tr.innerHTML = `
  6551. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6552. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6553. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6554. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6555. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6556. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6557. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6558. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6559. <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>
  6560. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6561. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6562. </td>
  6563. `;
  6564. tbody.appendChild(tr);
  6565. });
  6566. }
  6567. async function loadPPPProfiles() {
  6568. try {
  6569. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6570. const data = await res.json();
  6571. state.pppProfiles = Array.isArray(data) ? data : [];
  6572. const b = document.getElementById('ppp-badge-profiles');
  6573. if (b) b.innerText = state.pppProfiles.length;
  6574. const b2 = document.getElementById('profiles-count-badge');
  6575. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6576. // Populate profile selects across modals
  6577. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6578. selects.forEach(sid => {
  6579. const el = document.getElementById(sid);
  6580. if (!el) return;
  6581. const cur = el.value;
  6582. el.innerHTML = '';
  6583. state.pppProfiles.forEach(p => {
  6584. const opt = document.createElement('option');
  6585. opt.value = p.name;
  6586. opt.innerText = `${p.name} (${p.remote_address})`;
  6587. if (p.name === cur) opt.selected = true;
  6588. el.appendChild(opt);
  6589. });
  6590. });
  6591. renderPPPProfiles();
  6592. } catch (err) {
  6593. console.error('Failed to load PPP profiles:', err);
  6594. }
  6595. }
  6596. function renderPPPProfiles() {
  6597. const tbody = document.getElementById('profiles-table-body');
  6598. if (!tbody) return;
  6599. tbody.innerHTML = '';
  6600. (state.pppProfiles || []).forEach(p => {
  6601. const isDefault = p.name.startsWith('default');
  6602. const tr = document.createElement('tr');
  6603. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6604. tr.innerHTML = `
  6605. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6606. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6607. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6608. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6609. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6610. <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>
  6611. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6612. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6613. ${!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>`}
  6614. </td>
  6615. `;
  6616. tbody.appendChild(tr);
  6617. });
  6618. }
  6619. async function loadPPPServers() {
  6620. try {
  6621. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6622. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6623. fetch(`${API_BASE}/vpn/servers/pptp`),
  6624. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6625. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6626. ]);
  6627. if (pppoeRes.ok) {
  6628. state.pppoeServer = await pppoeRes.json();
  6629. const s = state.pppoeServer;
  6630. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6631. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6632. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6633. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6634. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6635. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6636. const pill = document.getElementById('pppoe-server-status-pill');
  6637. if (pill) {
  6638. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6639. 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';
  6640. }
  6641. setDotBadge('ppp-badge-pppoe-state', s.running);
  6642. }
  6643. if (pptpRes.ok) {
  6644. state.pptpServer = await pptpRes.json();
  6645. const s = state.pptpServer;
  6646. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6647. document.getElementById('pptp-server-port').value = s.port || 1723;
  6648. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6649. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6650. const pill = document.getElementById('pptp-server-status-pill');
  6651. if (pill) {
  6652. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6653. 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';
  6654. }
  6655. setDotBadge('ppp-badge-pptp-state', s.running);
  6656. }
  6657. if (l2tpRes.ok) {
  6658. state.l2tpServer = await l2tpRes.json();
  6659. const s = state.l2tpServer;
  6660. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6661. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6662. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6663. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6664. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6665. const pill = document.getElementById('l2tp-server-status-pill');
  6666. if (pill) {
  6667. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6668. 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';
  6669. }
  6670. setDotBadge('ppp-badge-l2tp-state', s.running);
  6671. }
  6672. if (ipsecRes.ok) {
  6673. state.ipsecServer = await ipsecRes.json();
  6674. const s = state.ipsecServer;
  6675. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6676. if (modalEn) modalEn.checked = !!s.enabled;
  6677. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6678. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6679. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6680. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6681. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6682. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6683. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6684. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6685. const pill = document.getElementById('modal-ipsec-server-status');
  6686. if (pill) {
  6687. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6688. 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';
  6689. }
  6690. }
  6691. } catch (err) {
  6692. console.error('Failed to load VPN servers:', err);
  6693. }
  6694. }
  6695. async function loadPPPSessions() {
  6696. try {
  6697. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6698. const data = await res.json();
  6699. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6700. const b = document.getElementById('ppp-badge-active');
  6701. if (b) b.innerText = state.pppActiveSessions.length;
  6702. const sideB = document.getElementById('badge-ppp-sessions');
  6703. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6704. renderPPPSessions();
  6705. } catch (err) {
  6706. console.error('Failed to load active PPP sessions:', err);
  6707. }
  6708. }
  6709. function renderPPPSessions() {
  6710. const tbody = document.getElementById('active-ppp-table-body');
  6711. const empty = document.getElementById('active-ppp-empty');
  6712. if (!tbody) return;
  6713. tbody.innerHTML = '';
  6714. const list = state.pppActiveSessions || [];
  6715. if (list.length === 0) {
  6716. empty?.classList.remove('hidden');
  6717. return;
  6718. }
  6719. empty?.classList.add('hidden');
  6720. list.forEach(s => {
  6721. const tr = document.createElement('tr');
  6722. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6723. tr.innerHTML = `
  6724. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6725. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6726. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6727. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6728. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6729. <td class="py-2.5 px-3 text-[11px]">
  6730. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6731. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6732. </td>
  6733. <td class="py-2.5 px-3 text-right font-sans">
  6734. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6735. </td>
  6736. `;
  6737. tbody.appendChild(tr);
  6738. });
  6739. }
  6740. async function disconnectPPPSession(iface) {
  6741. if (!confirm(`Disconnect session ${iface}?`)) return;
  6742. try {
  6743. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6744. if (res.ok) {
  6745. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6746. loadPPPSessions();
  6747. }
  6748. } catch (err) {
  6749. showToast('Error', err.message, 'error');
  6750. }
  6751. }
  6752. // PPP Secret Modal handlers
  6753. function openAddPPPSecretModal() {
  6754. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6755. document.getElementById('secret-modal-id').value = '';
  6756. document.getElementById('secret-modal-name').value = '';
  6757. document.getElementById('secret-modal-password').value = '';
  6758. document.getElementById('secret-modal-service').value = 'any';
  6759. document.getElementById('secret-modal-profile').value = 'default';
  6760. document.getElementById('secret-modal-local').value = '';
  6761. document.getElementById('secret-modal-remote').value = '';
  6762. document.getElementById('secret-modal-comment').value = '';
  6763. document.getElementById('secret-modal-disabled').checked = false;
  6764. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6765. }
  6766. function openEditPPPSecretModal(id) {
  6767. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6768. if (!s) return;
  6769. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6770. document.getElementById('secret-modal-id').value = s.id;
  6771. document.getElementById('secret-modal-name').value = s.name;
  6772. document.getElementById('secret-modal-password').value = s.password;
  6773. document.getElementById('secret-modal-service').value = s.service || 'any';
  6774. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6775. document.getElementById('secret-modal-local').value = s.local_address || '';
  6776. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6777. document.getElementById('secret-modal-comment').value = s.comment || '';
  6778. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6779. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6780. }
  6781. function closePPPSecretModal() {
  6782. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6783. }
  6784. async function submitSavePPPSecret(e) {
  6785. e.preventDefault();
  6786. const id = document.getElementById('secret-modal-id').value;
  6787. const name = document.getElementById('secret-modal-name').value.trim();
  6788. const password = document.getElementById('secret-modal-password').value.trim();
  6789. const service = document.getElementById('secret-modal-service').value;
  6790. const profile = document.getElementById('secret-modal-profile').value;
  6791. const local = document.getElementById('secret-modal-local').value.trim();
  6792. const remote = document.getElementById('secret-modal-remote').value.trim();
  6793. const comment = document.getElementById('secret-modal-comment').value.trim();
  6794. const disabled = document.getElementById('secret-modal-disabled').checked;
  6795. try {
  6796. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6797. method: 'POST',
  6798. headers: { 'Content-Type': 'application/json' },
  6799. body: JSON.stringify({
  6800. id,
  6801. name,
  6802. password,
  6803. service,
  6804. profile,
  6805. local_address: local,
  6806. remote_address: remote,
  6807. comment,
  6808. disabled
  6809. })
  6810. });
  6811. if (res.ok) {
  6812. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6813. closePPPSecretModal();
  6814. loadPPPSecrets();
  6815. } else {
  6816. const err = await res.json();
  6817. showToast('Error', err.message, 'error');
  6818. }
  6819. } catch (err) {
  6820. showToast('Error', err.message, 'error');
  6821. }
  6822. }
  6823. async function togglePPPSecretState(id, disabled) {
  6824. try {
  6825. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6826. method: 'POST',
  6827. headers: { 'Content-Type': 'application/json' },
  6828. body: JSON.stringify({ disabled })
  6829. });
  6830. if (res.ok) {
  6831. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6832. loadPPPSecrets();
  6833. }
  6834. } catch (err) {
  6835. showToast('Error', err.message, 'error');
  6836. }
  6837. }
  6838. async function deletePPPSecret(id) {
  6839. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6840. try {
  6841. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6842. if (res.ok) {
  6843. showToast('Deleted', 'Secret account removed', 'success');
  6844. loadPPPSecrets();
  6845. }
  6846. } catch (err) {
  6847. showToast('Error', err.message, 'error');
  6848. }
  6849. }
  6850. // PPP Profile Modal handlers
  6851. function openAddPPPProfileModal() {
  6852. document.getElementById('profile-modal-name').value = '';
  6853. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6854. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6855. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6856. document.getElementById('profile-modal-encryption').value = 'required';
  6857. document.getElementById('profile-modal-onlyone').checked = true;
  6858. document.getElementById('profile-modal-comment').value = '';
  6859. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6860. }
  6861. function closePPPProfileModal() {
  6862. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6863. }
  6864. async function submitSavePPPProfile(e) {
  6865. e.preventDefault();
  6866. const name = document.getElementById('profile-modal-name').value.trim();
  6867. const local = document.getElementById('profile-modal-local').value.trim();
  6868. const remote = document.getElementById('profile-modal-remote').value.trim();
  6869. const dns = document.getElementById('profile-modal-dns').value.trim();
  6870. const enc = document.getElementById('profile-modal-encryption').value;
  6871. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6872. const comment = document.getElementById('profile-modal-comment').value.trim();
  6873. try {
  6874. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6875. method: 'POST',
  6876. headers: { 'Content-Type': 'application/json' },
  6877. body: JSON.stringify({
  6878. id: name,
  6879. name,
  6880. local_address: local,
  6881. remote_address: remote,
  6882. dns_servers: dns,
  6883. use_encryption: enc,
  6884. only_one: onlyone,
  6885. comment
  6886. })
  6887. });
  6888. if (res.ok) {
  6889. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6890. closePPPProfileModal();
  6891. loadPPPProfiles();
  6892. } else {
  6893. const err = await res.json();
  6894. showToast('Error', err.message, 'error');
  6895. }
  6896. } catch (err) {
  6897. showToast('Error', err.message, 'error');
  6898. }
  6899. }
  6900. async function deletePPPProfile(name) {
  6901. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6902. try {
  6903. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6904. if (res.ok) {
  6905. showToast('Deleted', 'Profile removed', 'success');
  6906. loadPPPProfiles();
  6907. } else {
  6908. const err = await res.json();
  6909. showToast('Error', err.message, 'error');
  6910. }
  6911. } catch (err) {
  6912. showToast('Error', err.message, 'error');
  6913. }
  6914. }
  6915. // Server Config submissions
  6916. async function savePPPoEServerConfig(e) {
  6917. e.preventDefault();
  6918. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6919. const name = document.getElementById('pppoe-server-name').value.trim();
  6920. const iface = document.getElementById('pppoe-server-iface').value;
  6921. const profile = document.getElementById('pppoe-server-profile').value;
  6922. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6923. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6924. try {
  6925. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6926. method: 'POST',
  6927. headers: { 'Content-Type': 'application/json' },
  6928. body: JSON.stringify({
  6929. enabled,
  6930. service_name: name,
  6931. interface: iface,
  6932. default_profile: profile,
  6933. max_mtu: mtu,
  6934. max_mru: mtu,
  6935. one_session_per_host: onesession
  6936. })
  6937. });
  6938. if (res.ok) {
  6939. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6940. loadPPPServers();
  6941. fetchData(false);
  6942. } else {
  6943. const err = await res.json();
  6944. showToast('Error', err.message, 'error');
  6945. }
  6946. } catch (err) {
  6947. showToast('Error', err.message, 'error');
  6948. }
  6949. }
  6950. async function savePPTPServerConfig(e) {
  6951. e.preventDefault();
  6952. const enabled = document.getElementById('pptp-server-enabled').checked;
  6953. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6954. const profile = document.getElementById('pptp-server-profile').value;
  6955. const mppe = document.getElementById('pptp-server-mppe').checked;
  6956. try {
  6957. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6958. method: 'POST',
  6959. headers: { 'Content-Type': 'application/json' },
  6960. body: JSON.stringify({
  6961. enabled,
  6962. port,
  6963. default_profile: profile,
  6964. require_mppe: mppe
  6965. })
  6966. });
  6967. if (res.ok) {
  6968. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6969. loadPPPServers();
  6970. fetchData(false);
  6971. } else {
  6972. const err = await res.json();
  6973. showToast('Error', err.message, 'error');
  6974. }
  6975. } catch (err) {
  6976. showToast('Error', err.message, 'error');
  6977. }
  6978. }
  6979. async function saveL2TPServerConfig(e) {
  6980. e.preventDefault();
  6981. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6982. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6983. const profile = document.getElementById('l2tp-server-profile').value;
  6984. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6985. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6986. try {
  6987. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6988. method: 'POST',
  6989. headers: { 'Content-Type': 'application/json' },
  6990. body: JSON.stringify({
  6991. enabled,
  6992. port,
  6993. default_profile: profile,
  6994. use_ipsec: useipsec,
  6995. ipsec_secret: psk
  6996. })
  6997. });
  6998. if (res.ok) {
  6999. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7000. loadPPPServers();
  7001. fetchData(false);
  7002. } else {
  7003. const err = await res.json();
  7004. showToast('Error', err.message, 'error');
  7005. }
  7006. } catch (err) {
  7007. showToast('Error', err.message, 'error');
  7008. }
  7009. }
  7010. // IPSec Server Modal
  7011. function openIPSecServerModal() {
  7012. loadPPPServers();
  7013. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7014. }
  7015. function closeIPSecServerModal() {
  7016. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7017. }
  7018. async function submitSaveIPSecServer(e) {
  7019. e.preventDefault();
  7020. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7021. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7022. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7023. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7024. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7025. try {
  7026. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7027. method: 'POST',
  7028. headers: { 'Content-Type': 'application/json' },
  7029. body: JSON.stringify({
  7030. enabled,
  7031. preshared_key: psk,
  7032. pool_address: pool,
  7033. dns_servers: dns,
  7034. local_subnet: subnet
  7035. })
  7036. });
  7037. if (res.ok) {
  7038. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7039. closeIPSecServerModal();
  7040. loadPPPServers();
  7041. fetchData(false);
  7042. } else {
  7043. const err = await res.json();
  7044. showToast('Error', err.message, 'error');
  7045. }
  7046. } catch (err) {
  7047. showToast('Error', err.message, 'error');
  7048. }
  7049. }
  7050. // WireGuard Client Config Viewer
  7051. let currentWGClientConf = '';
  7052. async function openWGClientConfModal(iface, clientIP) {
  7053. try {
  7054. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7055. method: 'POST',
  7056. headers: { 'Content-Type': 'application/json' },
  7057. body: JSON.stringify({
  7058. interface: iface,
  7059. address: clientIP || '10.10.0.2/32',
  7060. dns: '1.1.1.1, 8.8.8.8'
  7061. })
  7062. });
  7063. if (res.ok) {
  7064. const data = await res.json();
  7065. currentWGClientConf = data.config;
  7066. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7067. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7068. } else {
  7069. const err = await res.json();
  7070. showToast('Error', err.message, 'error');
  7071. }
  7072. } catch (err) {
  7073. showToast('Error', err.message, 'error');
  7074. }
  7075. }
  7076. function closeWGClientConfModal() {
  7077. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7078. }
  7079. function copyWGClientConf() {
  7080. if (!currentWGClientConf) return;
  7081. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7082. }
  7083. function downloadWGClientConf() {
  7084. if (!currentWGClientConf) return;
  7085. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7086. const a = document.createElement('a');
  7087. a.href = URL.createObjectURL(blob);
  7088. a.download = 'wireguard-client.conf';
  7089. document.body.appendChild(a);
  7090. a.click();
  7091. document.body.removeChild(a);
  7092. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7093. }
  7094. // =========================================================================
  7095. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7096. // =========================================================================
  7097. state.activeDynSubTab = 'bgp-peers';
  7098. state.activeBgpSubTab = 'bgp-peers';
  7099. state.activeOspfTab = 'instances';
  7100. state.bgpInstance = null;
  7101. state.bgpPeers = [];
  7102. state.bgpNets = [];
  7103. state.bgpRoutes = [];
  7104. state.ospfInstance = null;
  7105. state.ospfInstances = [];
  7106. state.ospfAreas = [];
  7107. state.ospfAreaRanges = [];
  7108. state.ospfTemplates = [];
  7109. state.ospfLiveInterfaces = [];
  7110. state.ospfStaticNbrs = [];
  7111. state.ospfNeighbors = [];
  7112. state.ospfLSA = [];
  7113. state.ospfRoutes = [];
  7114. state.selectedOspfRow = {
  7115. instances: null,
  7116. areas: null,
  7117. 'area-ranges': null,
  7118. templates: null,
  7119. interfaces: null,
  7120. 'static-nbrs': null,
  7121. neighbors: null,
  7122. lsa: null,
  7123. };
  7124. state.ospfSort = {
  7125. instances: { col: 'name', asc: true },
  7126. areas: { col: 'name', asc: true },
  7127. ranges: { col: 'area', asc: true },
  7128. templates: { col: 'interfaces', asc: true },
  7129. live_ifaces: { col: 'interface', asc: true },
  7130. snbrs: { col: 'address', asc: true },
  7131. neighbors: { col: 'address', asc: true },
  7132. lsa: { col: 'instance', asc: true },
  7133. };
  7134. function switchBgpSubTab(subTab) {
  7135. state.activeBgpSubTab = subTab;
  7136. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7137. tabs.forEach(t => {
  7138. const el = document.getElementById(`dyn-subtab-${t}`);
  7139. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7140. if (el) el.classList.toggle('hidden', t !== subTab);
  7141. if (btn) {
  7142. if (t === subTab) {
  7143. 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';
  7144. } else {
  7145. 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';
  7146. }
  7147. }
  7148. });
  7149. }
  7150. function switchOspfTab(tabName) {
  7151. state.activeOspfTab = tabName;
  7152. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7153. tabs.forEach(t => {
  7154. const pane = document.getElementById(`ospf-pane-${t}`);
  7155. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7156. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7157. if (btn) {
  7158. if (t === tabName) {
  7159. 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';
  7160. } else {
  7161. 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';
  7162. }
  7163. }
  7164. });
  7165. }
  7166. function switchOspfSubTab(tab) {
  7167. // Legacy alias
  7168. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7169. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7170. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7171. else switchOspfTab('instances');
  7172. }
  7173. function switchDynSubTab(subTab) {
  7174. if (subTab.startsWith('bgp')) {
  7175. if (state.activeTab !== 'bgp') navigate('bgp');
  7176. switchBgpSubTab(subTab);
  7177. } else if (subTab.startsWith('ospf')) {
  7178. if (state.activeTab !== 'ospf') navigate('ospf');
  7179. switchOspfTab('instances');
  7180. }
  7181. }
  7182. async function loadDynamicRouting(showToastMsg = false) {
  7183. try {
  7184. const fetchSafeJson = async (url) => {
  7185. try {
  7186. const r = await fetch(url);
  7187. return r.ok ? await r.json() : null;
  7188. } catch (e) {
  7189. return null;
  7190. }
  7191. };
  7192. const [
  7193. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7194. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7195. selectRules, commLists, asLists
  7196. ] = await Promise.all([
  7197. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7198. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7199. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7200. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7201. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7202. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7203. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7204. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7205. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7206. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7207. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7208. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7209. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7210. fetchSafeJson(`${API_BASE}/routing/filters`),
  7211. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7212. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7213. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7214. ]);
  7215. if (sum) state.dynSummary = sum;
  7216. if (bgpInst) state.bgpInstance = bgpInst;
  7217. if (bgpPeers) state.bgpPeers = bgpPeers;
  7218. if (bgpNets) state.bgpNets = bgpNets;
  7219. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7220. if (ospfInsts) state.ospfInstances = ospfInsts;
  7221. if (ospfAreas) state.ospfAreas = ospfAreas;
  7222. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7223. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7224. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7225. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7226. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7227. if (ospfLsa) state.ospfLSA = ospfLsa;
  7228. if (filters) state.routingFilters = filters;
  7229. if (selectRules) state.routingSelectRules = selectRules;
  7230. if (commLists) state.routingCommunityLists = commLists;
  7231. if (asLists) state.routingASLists = asLists;
  7232. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7233. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7234. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7235. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7236. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7237. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7238. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7239. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7240. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7241. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7242. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7243. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7244. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7245. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7246. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7247. } catch (err) {
  7248. console.error('Failed to load dynamic routing:', err);
  7249. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7250. }
  7251. }
  7252. async function loadOspfAll() {
  7253. await loadDynamicRouting(true);
  7254. }
  7255. function renderBgpStatusPill() {
  7256. const pill = document.getElementById('bgp-live-status-pill');
  7257. if (!pill) return;
  7258. const inst = state.bgpInstance;
  7259. if (!inst || !inst.enabled) {
  7260. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7261. pill.innerText = 'BGP DISABLED';
  7262. } else if (inst.running) {
  7263. 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';
  7264. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7265. } else {
  7266. 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';
  7267. pill.innerText = 'BGP STARTING...';
  7268. }
  7269. }
  7270. function renderBgpPeers() {
  7271. const tbody = document.getElementById('bgp-peers-table-body');
  7272. if (!tbody) return;
  7273. const empty = document.getElementById('bgp-peers-empty');
  7274. const countBadge = document.getElementById('bgp-peers-count-badge');
  7275. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7276. const peers = state.bgpPeers || [];
  7277. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7278. if (navBadge) navBadge.innerText = peers.length;
  7279. if (peers.length === 0) {
  7280. tbody.innerHTML = '';
  7281. if (empty) empty.classList.remove('hidden');
  7282. return;
  7283. }
  7284. if (empty) empty.classList.add('hidden');
  7285. tbody.innerHTML = peers.map(p => {
  7286. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7287. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7288. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7289. let stateBadge = '';
  7290. if (p.disabled) {
  7291. 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>';
  7292. } else if (p.state === 'Established') {
  7293. 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>';
  7294. } else if (p.state === 'Connect' || p.state === 'Active') {
  7295. 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>`;
  7296. } else {
  7297. 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>`;
  7298. }
  7299. return `
  7300. <tr class="hover:bg-slate-800/40 transition">
  7301. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7302. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7303. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7304. <td class="py-2.5 px-3">
  7305. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7306. ${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>`}
  7307. </td>
  7308. <td class="py-2.5 px-3">${stateBadge}</td>
  7309. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7310. <td class="py-2.5 px-3 text-slate-300">
  7311. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7312. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7313. </td>
  7314. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7315. ${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> ` : ''}
  7316. ${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>` : ''}
  7317. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7318. </td>
  7319. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7320. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7321. <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'}">
  7322. ${p.disabled ? 'Enable' : 'Disable'}
  7323. </button>
  7324. <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">
  7325. Edit
  7326. </button>
  7327. <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">
  7328. Delete
  7329. </button>
  7330. </td>
  7331. </tr>
  7332. `;
  7333. }).join('');
  7334. }
  7335. function renderBgpNetworks() {
  7336. const tbody = document.getElementById('bgp-nets-table-body');
  7337. if (!tbody) return;
  7338. const empty = document.getElementById('bgp-nets-empty');
  7339. const countBadge = document.getElementById('bgp-nets-count-badge');
  7340. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7341. const nets = state.bgpNets || [];
  7342. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7343. if (navBadge) navBadge.innerText = nets.length;
  7344. if (nets.length === 0) {
  7345. tbody.innerHTML = '';
  7346. if (empty) empty.classList.remove('hidden');
  7347. return;
  7348. }
  7349. if (empty) empty.classList.add('hidden');
  7350. tbody.innerHTML = nets.map(n => `
  7351. <tr class="hover:bg-slate-800/40 transition">
  7352. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7353. <td class="py-2.5 px-3">
  7354. ${n.disabled
  7355. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7356. : '<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>'}
  7357. </td>
  7358. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7359. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7360. <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">
  7361. Delete
  7362. </button>
  7363. </td>
  7364. </tr>
  7365. `).join('');
  7366. }
  7367. function renderBgpRoutes() {
  7368. const tbody = document.getElementById('bgp-routes-table-body');
  7369. if (!tbody) return;
  7370. const empty = document.getElementById('bgp-routes-empty');
  7371. const countBadge = document.getElementById('bgp-routes-count-badge');
  7372. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7373. const routes = state.bgpRoutes || [];
  7374. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7375. if (navBadge) navBadge.innerText = routes.length;
  7376. if (routes.length === 0) {
  7377. tbody.innerHTML = '';
  7378. if (empty) empty.classList.remove('hidden');
  7379. return;
  7380. }
  7381. if (empty) empty.classList.add('hidden');
  7382. tbody.innerHTML = routes.map(r => `
  7383. <tr class="hover:bg-slate-800/40 transition">
  7384. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7385. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7386. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7387. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7388. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7389. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7390. </tr>
  7391. `).join('');
  7392. }
  7393. // =========================================================================
  7394. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7395. // =========================================================================
  7396. function sortOspfTable(tab, col) {
  7397. if (!state.ospfSort) state.ospfSort = {};
  7398. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7399. if (state.ospfSort[tab].col === col) {
  7400. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7401. } else {
  7402. state.ospfSort[tab].col = col;
  7403. state.ospfSort[tab].asc = true;
  7404. }
  7405. const asc = state.ospfSort[tab].asc;
  7406. let list = [];
  7407. if (tab === 'instances') list = state.ospfInstances || [];
  7408. else if (tab === 'areas') list = state.ospfAreas || [];
  7409. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7410. else if (tab === 'templates') list = state.ospfTemplates || [];
  7411. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7412. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7413. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7414. else if (tab === 'lsa') list = state.ospfLSA || [];
  7415. list.sort((a, b) => {
  7416. let valA = a[col] ?? '';
  7417. let valB = b[col] ?? '';
  7418. if (typeof valA === 'number' && typeof valB === 'number') {
  7419. return asc ? valA - valB : valB - valA;
  7420. }
  7421. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7422. });
  7423. if (tab === 'instances') renderOspfInstances();
  7424. else if (tab === 'areas') renderOspfAreas();
  7425. else if (tab === 'ranges') renderOspfAreaRanges();
  7426. else if (tab === 'templates') renderOspfTemplates();
  7427. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7428. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7429. else if (tab === 'neighbors') renderOspfNeighbors();
  7430. else if (tab === 'lsa') renderOspfLSA();
  7431. }
  7432. function selectOspfRow(tab, id) {
  7433. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7434. state.selectedOspfRow[tab] = id;
  7435. if (tab === 'instances') {
  7436. renderOspfInstances();
  7437. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7438. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7439. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7440. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7441. if (btnEn) btnEn.disabled = false;
  7442. if (btnDis) btnDis.disabled = false;
  7443. if (btnRem) btnRem.disabled = false;
  7444. if (btnCom) btnCom.disabled = false;
  7445. } else if (tab === 'areas') {
  7446. renderOspfAreas();
  7447. const btnEn = document.getElementById('btn-ospf-area-enable');
  7448. const btnDis = document.getElementById('btn-ospf-area-disable');
  7449. const btnRem = document.getElementById('btn-ospf-area-remove');
  7450. const btnCom = document.getElementById('btn-ospf-area-comment');
  7451. if (btnEn) btnEn.disabled = false;
  7452. if (btnDis) btnDis.disabled = false;
  7453. if (btnRem) btnRem.disabled = false;
  7454. if (btnCom) btnCom.disabled = false;
  7455. } else if (tab === 'ranges') {
  7456. renderOspfAreaRanges();
  7457. const btnEn = document.getElementById('btn-ospf-range-enable');
  7458. const btnDis = document.getElementById('btn-ospf-range-disable');
  7459. const btnRem = document.getElementById('btn-ospf-range-remove');
  7460. const btnCom = document.getElementById('btn-ospf-range-comment');
  7461. if (btnEn) btnEn.disabled = false;
  7462. if (btnDis) btnDis.disabled = false;
  7463. if (btnRem) btnRem.disabled = false;
  7464. if (btnCom) btnCom.disabled = false;
  7465. } else if (tab === 'templates') {
  7466. renderOspfTemplates();
  7467. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7468. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7469. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7470. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7471. if (btnEn) btnEn.disabled = false;
  7472. if (btnDis) btnDis.disabled = false;
  7473. if (btnRem) btnRem.disabled = false;
  7474. if (btnCom) btnCom.disabled = false;
  7475. } else if (tab === 'snbrs') {
  7476. renderOspfStaticNbrs();
  7477. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7478. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7479. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7480. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7481. if (btnEn) btnEn.disabled = false;
  7482. if (btnDis) btnDis.disabled = false;
  7483. if (btnRem) btnRem.disabled = false;
  7484. if (btnCom) btnCom.disabled = false;
  7485. }
  7486. }
  7487. // TAB 1: INSTANCES
  7488. function renderOspfInstances() {
  7489. const tbody = document.getElementById('ospf-instances-table-body');
  7490. if (!tbody) return;
  7491. const countEl = document.getElementById('ospf-instances-footer-count');
  7492. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7493. let list = state.ospfInstances || [];
  7494. if (filter) {
  7495. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7496. }
  7497. if (countEl) countEl.innerText = list.length;
  7498. const selId = state.selectedOspfRow?.instances;
  7499. tbody.innerHTML = list.map((inst, idx) => {
  7500. const isSel = inst.id === selId;
  7501. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7502. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7503. return `
  7504. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7505. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7506. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7507. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7508. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7509. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7510. </td>
  7511. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7512. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7513. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7514. </tr>
  7515. `;
  7516. }).join('');
  7517. }
  7518. // TAB 2: AREAS
  7519. function renderOspfAreas() {
  7520. const tbody = document.getElementById('ospf-areas-table-body');
  7521. if (!tbody) return;
  7522. const countEl = document.getElementById('ospf-areas-footer-count');
  7523. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7524. let list = state.ospfAreas || [];
  7525. if (filter) {
  7526. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7527. }
  7528. if (countEl) countEl.innerText = list.length;
  7529. const selId = state.selectedOspfRow?.areas;
  7530. tbody.innerHTML = list.map((a, idx) => {
  7531. const isSel = a.id === selId;
  7532. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7533. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7534. return `
  7535. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7536. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7537. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7538. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7539. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7540. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7541. </td>
  7542. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7543. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7544. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7545. </tr>
  7546. `;
  7547. }).join('');
  7548. }
  7549. // TAB 3: AREA RANGES
  7550. function renderOspfAreaRanges() {
  7551. const tbody = document.getElementById('ospf-ranges-table-body');
  7552. if (!tbody) return;
  7553. const countEl = document.getElementById('ospf-ranges-footer-count');
  7554. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7555. let list = state.ospfAreaRanges || [];
  7556. if (filter) {
  7557. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7558. }
  7559. if (countEl) countEl.innerText = list.length;
  7560. const selId = state.selectedOspfRow?.['area-ranges'];
  7561. tbody.innerHTML = list.map((r, idx) => {
  7562. const isSel = r.id === selId;
  7563. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7564. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7565. return `
  7566. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7567. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7568. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7569. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7570. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7571. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7572. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7573. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7574. </tr>
  7575. `;
  7576. }).join('');
  7577. }
  7578. // TAB 4: INTERFACE TEMPLATES
  7579. function renderOspfTemplates() {
  7580. const tbody = document.getElementById('ospf-templates-table-body');
  7581. if (!tbody) return;
  7582. const countEl = document.getElementById('ospf-templates-footer-count');
  7583. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7584. let list = state.ospfTemplates || [];
  7585. if (filter) {
  7586. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7587. }
  7588. if (countEl) countEl.innerText = list.length;
  7589. const selId = state.selectedOspfRow?.templates;
  7590. tbody.innerHTML = list.map((t, idx) => {
  7591. const isSel = t.id === selId;
  7592. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7593. const ifaces = t.interfaces || t.interface || 'all';
  7594. const nets = t.networks || t.network || '';
  7595. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7596. return `
  7597. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7598. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7599. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7600. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7601. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7602. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7603. </td>
  7604. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7605. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7606. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7607. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7608. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7609. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7610. </tr>
  7611. `;
  7612. }).join('');
  7613. }
  7614. // TAB 5: LIVE INTERFACES
  7615. function renderOspfLiveInterfaces() {
  7616. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7617. if (!tbody) return;
  7618. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7619. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7620. let list = state.ospfLiveInterfaces || [];
  7621. if (filter) {
  7622. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7623. }
  7624. if (countEl) countEl.innerText = list.length;
  7625. tbody.innerHTML = list.map(i => `
  7626. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7627. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7628. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7629. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7630. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7631. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7632. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7633. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7634. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7635. </tr>
  7636. `).join('');
  7637. }
  7638. // TAB 6: STATIC NEIGHBORS
  7639. function renderOspfStaticNbrs() {
  7640. const tbody = document.getElementById('ospf-snbrs-table-body');
  7641. if (!tbody) return;
  7642. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7643. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7644. let list = state.ospfStaticNbrs || [];
  7645. if (filter) {
  7646. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7647. }
  7648. if (countEl) countEl.innerText = list.length;
  7649. const selId = state.selectedOspfRow?.['static-nbrs'];
  7650. tbody.innerHTML = list.map((n, idx) => {
  7651. const isSel = n.id === selId;
  7652. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7653. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7654. return `
  7655. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7656. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7657. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7658. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7659. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7660. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7661. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7662. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7663. </tr>
  7664. `;
  7665. }).join('');
  7666. }
  7667. // TAB 7: LIVE NEIGHBORS
  7668. function renderOspfNeighbors() {
  7669. const tbody = document.getElementById('ospf-neighbors-table-body');
  7670. if (!tbody) return;
  7671. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7672. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7673. let list = state.ospfNeighbors || [];
  7674. if (filter) {
  7675. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7676. }
  7677. if (countEl) countEl.innerText = list.length;
  7678. tbody.innerHTML = list.map(n => `
  7679. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7680. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7681. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7682. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7683. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7684. </td>
  7685. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7686. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7687. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7688. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7689. </tr>
  7690. `).join('');
  7691. }
  7692. // TAB 8: LINK-STATE DATABASE (LSA)
  7693. function renderOspfLSA() {
  7694. const tbody = document.getElementById('ospf-lsa-table-body');
  7695. if (!tbody) return;
  7696. const countEl = document.getElementById('ospf-lsa-footer-count');
  7697. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7698. let list = state.ospfLSA || [];
  7699. if (filter) {
  7700. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7701. }
  7702. if (countEl) countEl.innerText = list.length;
  7703. tbody.innerHTML = list.map(l => `
  7704. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7705. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7706. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7707. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7708. </td>
  7709. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7710. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7711. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7712. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7713. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7714. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7715. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7716. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7717. </tr>
  7718. `).join('');
  7719. }
  7720. function renderOspfStatusPill() {
  7721. // Maintained for backward compatibility
  7722. const pill = document.getElementById('ospf-live-status-pill');
  7723. if (!pill) return;
  7724. 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';
  7725. pill.innerText = 'OSPF ACTIVE';
  7726. }
  7727. function renderOspfInterfaces() {
  7728. renderOspfTemplates();
  7729. }
  7730. function renderOspfRoutes() {
  7731. // Routes retained in background
  7732. }
  7733. // BGP Modals & Actions
  7734. function openBgpInstanceModal() {
  7735. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7736. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7737. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7738. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7739. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7740. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7741. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7742. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7743. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7744. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7745. }
  7746. function closeBgpInstanceModal() {
  7747. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7748. }
  7749. async function submitBgpInstance(e) {
  7750. e.preventDefault();
  7751. const payload = {
  7752. enabled: document.getElementById('modal-bgp-enabled').checked,
  7753. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7754. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7755. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7756. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7757. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7758. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7759. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7760. };
  7761. try {
  7762. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7763. method: 'POST',
  7764. headers: { 'Content-Type': 'application/json' },
  7765. body: JSON.stringify(payload)
  7766. });
  7767. if (res.ok) {
  7768. closeBgpInstanceModal();
  7769. showToast('Success', 'BGP instance configuration updated', 'success');
  7770. loadDynamicRouting();
  7771. } else {
  7772. const err = await res.json();
  7773. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7774. }
  7775. } catch (err) {
  7776. showToast('Error', err.message, 'error');
  7777. }
  7778. }
  7779. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7780. function switchBgpPeerModalTab(tab) {
  7781. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7782. tabs.forEach(t => {
  7783. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7784. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7785. if (t === tab) {
  7786. if (pane) pane.classList.remove('hidden');
  7787. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7788. } else {
  7789. if (pane) pane.classList.add('hidden');
  7790. 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';
  7791. }
  7792. });
  7793. }
  7794. function addOutputNetworkRow(val = '') {
  7795. const container = document.getElementById('modal-bgp-output-networks-container');
  7796. if (!container) return;
  7797. const row = document.createElement('div');
  7798. row.className = 'flex items-center gap-2 output-net-row';
  7799. row.innerHTML = `
  7800. <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">
  7801. <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>
  7802. `;
  7803. container.appendChild(row);
  7804. }
  7805. function parseBgpTime(val) {
  7806. if (!val) return 0;
  7807. val = String(val).trim();
  7808. if (val.includes(':')) {
  7809. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7810. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7811. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7812. }
  7813. return parseInt(val, 10) || 0;
  7814. }
  7815. function formatBgpTime(secs) {
  7816. if (!secs || secs <= 0) return '00:00:00';
  7817. const h = Math.floor(secs / 3600);
  7818. const m = Math.floor((secs % 3600) / 60);
  7819. const s = secs % 60;
  7820. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7821. }
  7822. function populateBgpRoutingTables() {
  7823. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7824. if (!sel) return;
  7825. const cur = sel.value || 'main';
  7826. sel.innerHTML = '<option value="main">main</option>';
  7827. (state.routingTables || []).forEach(t => {
  7828. if (t.name !== 'main') {
  7829. const opt = document.createElement('option');
  7830. opt.value = t.name;
  7831. opt.innerText = t.name;
  7832. sel.appendChild(opt);
  7833. }
  7834. });
  7835. sel.value = cur;
  7836. }
  7837. function openAddBgpPeerModal() {
  7838. document.getElementById('bgp-peer-form').reset();
  7839. document.getElementById('modal-bgp-peer-id').value = '';
  7840. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7841. // General Tab
  7842. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7843. document.getElementById('modal-bgp-peer-comment').value = '';
  7844. document.getElementById('modal-bgp-peer-name').value = '';
  7845. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7846. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7847. document.getElementById('modal-bgp-peer-local-as').value = '';
  7848. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7849. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7850. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7851. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7852. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7853. document.getElementById('modal-bgp-peer-router-id').value = '';
  7854. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7855. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7856. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7857. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7858. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7859. document.getElementById('modal-bgp-peer-local-port').value = '';
  7860. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7861. document.getElementById('modal-bgp-peer-password').value = '';
  7862. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7863. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7864. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7865. document.getElementById('modal-bgp-peer-connect').checked = true;
  7866. document.getElementById('modal-bgp-peer-listen').checked = true;
  7867. // Extra Tab
  7868. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7869. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7870. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7871. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7872. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7873. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7874. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7875. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7876. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7877. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7878. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7879. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7880. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7881. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7882. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7883. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7884. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7885. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7886. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7887. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7888. // Attributes Tab
  7889. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7890. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7891. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7892. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7893. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7894. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7895. // Filter Tab
  7896. populateFilterChainsDatalist();
  7897. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7898. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7899. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7900. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7901. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7902. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7903. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7904. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7905. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7906. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7907. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7908. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7909. populateBgpRoutingTables();
  7910. const container = document.getElementById('modal-bgp-output-networks-container');
  7911. if (container) {
  7912. container.innerHTML = '';
  7913. addOutputNetworkRow('');
  7914. }
  7915. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7916. if (removeBtn) removeBtn.classList.add('hidden');
  7917. switchBgpPeerModalTab('general');
  7918. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7919. }
  7920. function populateFilterChainsDatalist() {
  7921. const dl = document.getElementById('filter-chains-list');
  7922. if (!dl) return;
  7923. const chains = new Set();
  7924. (state.routingFilters || []).forEach(f => {
  7925. if (f.chain) chains.add(f.chain);
  7926. });
  7927. if (chains.size === 0) {
  7928. chains.add('awmn');
  7929. chains.add('bgp-in');
  7930. chains.add('bgp-out');
  7931. }
  7932. dl.innerHTML = '';
  7933. chains.forEach(c => {
  7934. const opt = document.createElement('option');
  7935. opt.value = c;
  7936. dl.appendChild(opt);
  7937. });
  7938. }
  7939. function openEditBgpPeerModal(id) {
  7940. const p = (state.bgpPeers || []).find(item => item.id === id);
  7941. if (!p) return;
  7942. populateBgpRoutingTables();
  7943. populateFilterChainsDatalist();
  7944. document.getElementById('modal-bgp-peer-id').value = p.id;
  7945. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7946. // General Tab
  7947. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7948. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7949. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7950. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7951. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7952. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7953. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7954. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7955. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7956. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7957. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7958. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7959. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7960. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7961. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7962. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7963. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7964. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7965. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7966. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7967. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7968. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7969. // Extra Tab
  7970. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7971. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7972. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7973. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7974. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7975. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7976. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7977. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7978. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7979. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7980. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7981. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7982. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7983. 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;
  7984. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7985. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7986. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7987. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7988. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7989. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7990. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7991. // Attributes Tab
  7992. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7993. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7994. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7995. 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;
  7996. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7997. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7998. // Filter Tab
  7999. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8000. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8001. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8002. 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 || '';
  8003. 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 || '';
  8004. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8005. 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 || '';
  8006. 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 || '';
  8007. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8008. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8009. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8010. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8011. // Output Networks
  8012. const container = document.getElementById('modal-bgp-output-networks-container');
  8013. if (container) {
  8014. container.innerHTML = '';
  8015. if (p.output_networks && p.output_networks.length > 0) {
  8016. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8017. } else {
  8018. addOutputNetworkRow('');
  8019. }
  8020. }
  8021. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8022. if (removeBtn) removeBtn.classList.remove('hidden');
  8023. switchBgpPeerModalTab('general');
  8024. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8025. }
  8026. function copyCurrentBgpPeer() {
  8027. document.getElementById('modal-bgp-peer-id').value = '';
  8028. const nameEl = document.getElementById('modal-bgp-peer-name');
  8029. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8030. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8031. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8032. if (removeBtn) removeBtn.classList.add('hidden');
  8033. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8034. }
  8035. function removeCurrentBgpPeer() {
  8036. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8037. if (!id) return;
  8038. deleteBgpPeer(id);
  8039. closeBgpPeerModal();
  8040. }
  8041. function closeBgpPeerModal() {
  8042. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8043. }
  8044. function getBgpPeerFormData() {
  8045. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8046. const outputNetworks = [];
  8047. netInputs.forEach(inp => {
  8048. const v = inp.value.trim();
  8049. if (v) outputNetworks.push(v);
  8050. });
  8051. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8052. return {
  8053. id: document.getElementById('modal-bgp-peer-id').value,
  8054. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8055. enabled: enabled,
  8056. disabled: !enabled,
  8057. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8058. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8059. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8060. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8061. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8062. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8063. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8064. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8065. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8066. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8067. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8068. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8069. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8070. password: document.getElementById('modal-bgp-peer-password').value,
  8071. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8072. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8073. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8074. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8075. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8076. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8077. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8078. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8079. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8080. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8081. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8082. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8083. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8084. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8085. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8086. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8087. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8088. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8089. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8090. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8091. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8092. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8093. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8094. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8095. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8096. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8097. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8098. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8099. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8100. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8101. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8102. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8103. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8104. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8105. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8106. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8107. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8108. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8109. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8110. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8111. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8112. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8113. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8114. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8115. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8116. output_networks: outputNetworks
  8117. };
  8118. }
  8119. async function submitBgpPeer(e) {
  8120. if (e) e.preventDefault();
  8121. const payload = getBgpPeerFormData();
  8122. try {
  8123. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8124. method: 'POST',
  8125. headers: { 'Content-Type': 'application/json' },
  8126. body: JSON.stringify(payload)
  8127. });
  8128. if (res.ok) {
  8129. closeBgpPeerModal();
  8130. showToast('Success', 'BGP Connection saved', 'success');
  8131. loadDynamicRouting();
  8132. } else {
  8133. const err = await res.json();
  8134. showToast('Error', err.error || 'Failed to save peer', 'error');
  8135. }
  8136. } catch (err) {
  8137. showToast('Error', err.message, 'error');
  8138. }
  8139. }
  8140. async function applyBgpPeerModal(e) {
  8141. if (e) e.preventDefault();
  8142. const payload = getBgpPeerFormData();
  8143. try {
  8144. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8145. method: 'POST',
  8146. headers: { 'Content-Type': 'application/json' },
  8147. body: JSON.stringify(payload)
  8148. });
  8149. if (res.ok) {
  8150. const data = await res.json();
  8151. if (data.peer && data.peer.id) {
  8152. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8153. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8154. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8155. }
  8156. showToast('Applied', 'BGP Connection applied', 'success');
  8157. loadDynamicRouting();
  8158. } else {
  8159. const err = await res.json();
  8160. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8161. }
  8162. } catch (err) {
  8163. showToast('Error', err.message, 'error');
  8164. }
  8165. }
  8166. async function deleteBgpPeer(id) {
  8167. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8168. try {
  8169. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8170. if (res.ok) {
  8171. showToast('Deleted', 'BGP peer removed', 'success');
  8172. loadDynamicRouting();
  8173. }
  8174. } catch (err) {
  8175. showToast('Error', err.message, 'error');
  8176. }
  8177. }
  8178. async function toggleBgpPeerState(id, disabled) {
  8179. try {
  8180. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8181. method: 'POST',
  8182. headers: { 'Content-Type': 'application/json' },
  8183. body: JSON.stringify({ disabled })
  8184. });
  8185. if (res.ok) {
  8186. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8187. loadDynamicRouting();
  8188. }
  8189. } catch (err) {
  8190. showToast('Error', err.message, 'error');
  8191. }
  8192. }
  8193. function openAddBgpNetworkModal() {
  8194. document.getElementById('bgp-network-form').reset();
  8195. document.getElementById('modal-bgp-net-id').value = '';
  8196. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8197. }
  8198. function closeBgpNetworkModal() {
  8199. document.getElementById('bgp-network-modal').classList.add('hidden');
  8200. }
  8201. async function submitBgpNetwork(e) {
  8202. e.preventDefault();
  8203. const payload = {
  8204. id: document.getElementById('modal-bgp-net-id').value,
  8205. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8206. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8207. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8208. };
  8209. try {
  8210. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8211. method: 'POST',
  8212. headers: { 'Content-Type': 'application/json' },
  8213. body: JSON.stringify(payload)
  8214. });
  8215. if (res.ok) {
  8216. closeBgpNetworkModal();
  8217. showToast('Success', 'BGP network advertisement saved', 'success');
  8218. loadDynamicRouting();
  8219. } else {
  8220. const err = await res.json();
  8221. showToast('Error', err.error || 'Failed to save network', 'error');
  8222. }
  8223. } catch (err) {
  8224. showToast('Error', err.message, 'error');
  8225. }
  8226. }
  8227. async function deleteBgpNetwork(id) {
  8228. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8229. try {
  8230. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8231. if (res.ok) {
  8232. showToast('Deleted', 'Network advertisement removed', 'success');
  8233. loadDynamicRouting();
  8234. }
  8235. } catch (err) {
  8236. showToast('Error', err.message, 'error');
  8237. }
  8238. }
  8239. // =========================================================================
  8240. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8241. // =========================================================================
  8242. // --- 1. OSPF INSTANCE ---
  8243. function openOspfInstanceModal(id = null) {
  8244. const isEdit = !!id;
  8245. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8246. id: '',
  8247. name: 'Default',
  8248. version: 2,
  8249. vrf: 'main',
  8250. router_id: '192.168.131.56',
  8251. routing_table: 'main',
  8252. enabled: true,
  8253. redistribute_connected: false,
  8254. redistribute_static: true,
  8255. redistribute_bgp: false,
  8256. comment: ''
  8257. };
  8258. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8259. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8260. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8261. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8262. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8263. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8264. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8265. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8266. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8267. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8268. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8269. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8270. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8271. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8272. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8273. }
  8274. function openEditOspfInstanceModal(id) {
  8275. openOspfInstanceModal(id);
  8276. }
  8277. function closeOspfInstanceModal() {
  8278. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8279. }
  8280. async function submitOspfInstance(e) {
  8281. if (e) e.preventDefault();
  8282. const payload = {
  8283. id: document.getElementById('modal-ospf-inst-id').value,
  8284. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8285. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8286. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8287. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8288. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8289. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8290. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8291. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8292. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8293. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8294. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8295. };
  8296. try {
  8297. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8298. method: 'POST',
  8299. headers: { 'Content-Type': 'application/json' },
  8300. body: JSON.stringify(payload)
  8301. });
  8302. if (res.ok) {
  8303. closeOspfInstanceModal();
  8304. showToast('Saved', 'OSPF instance updated', 'success');
  8305. loadDynamicRouting();
  8306. } else {
  8307. const err = await res.json();
  8308. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8309. }
  8310. } catch (err) {
  8311. showToast('Error', err.message, 'error');
  8312. }
  8313. }
  8314. function applyOspfInstanceForm() {
  8315. submitOspfInstance(null);
  8316. }
  8317. function copyOspfInstance() {
  8318. document.getElementById('modal-ospf-inst-id').value = '';
  8319. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8320. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8321. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8322. }
  8323. async function deleteCurrentOspfInstance() {
  8324. const id = document.getElementById('modal-ospf-inst-id').value;
  8325. if (!id) return;
  8326. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8327. try {
  8328. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8329. if (res.ok) {
  8330. closeOspfInstanceModal();
  8331. showToast('Removed', 'OSPF instance deleted', 'success');
  8332. loadDynamicRouting();
  8333. }
  8334. } catch (err) {
  8335. showToast('Error', err.message, 'error');
  8336. }
  8337. }
  8338. async function enableSelectedOspfInstance() {
  8339. const id = state.selectedOspfRow?.instances;
  8340. if (!id) return;
  8341. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8342. method: 'POST',
  8343. headers: { 'Content-Type': 'application/json' },
  8344. body: JSON.stringify({ disabled: false })
  8345. });
  8346. loadDynamicRouting();
  8347. }
  8348. async function disableSelectedOspfInstance() {
  8349. const id = state.selectedOspfRow?.instances;
  8350. if (!id) return;
  8351. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8352. method: 'POST',
  8353. headers: { 'Content-Type': 'application/json' },
  8354. body: JSON.stringify({ disabled: true })
  8355. });
  8356. loadDynamicRouting();
  8357. }
  8358. async function removeSelectedOspfInstance() {
  8359. const id = state.selectedOspfRow?.instances;
  8360. if (!id) return;
  8361. if (!confirm('Delete selected OSPF instance?')) return;
  8362. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8363. loadDynamicRouting();
  8364. }
  8365. async function promptCommentOspfInstance() {
  8366. const id = state.selectedOspfRow?.instances;
  8367. if (!id) return;
  8368. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8369. if (!inst) return;
  8370. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8371. if (comment === null) return;
  8372. inst.comment = comment;
  8373. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8374. method: 'POST',
  8375. headers: { 'Content-Type': 'application/json' },
  8376. body: JSON.stringify(inst)
  8377. });
  8378. loadDynamicRouting();
  8379. }
  8380. // --- 2. OSPF AREA ---
  8381. function populateOspfAreaDropdowns() {
  8382. const instSelect = document.getElementById('modal-ospf-area-instance');
  8383. if (instSelect) {
  8384. const cur = instSelect.value;
  8385. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8386. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8387. if (cur) instSelect.value = cur;
  8388. }
  8389. }
  8390. function openOspfAreaModal(id = null) {
  8391. const isEdit = !!id;
  8392. populateOspfAreaDropdowns();
  8393. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8394. id: '',
  8395. name: 'Default',
  8396. instance: 'Default',
  8397. area_id: '0.0.0.0',
  8398. area_type: 'default',
  8399. default_cost: 1,
  8400. no_summaries: false,
  8401. disabled: false,
  8402. comment: ''
  8403. };
  8404. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8405. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8406. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8407. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8408. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8409. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8410. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8411. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8412. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8413. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8414. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8415. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8416. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8417. }
  8418. function openEditOspfAreaModal(id) {
  8419. openOspfAreaModal(id);
  8420. }
  8421. function closeOspfAreaModal() {
  8422. document.getElementById('ospf-area-modal').classList.add('hidden');
  8423. }
  8424. async function submitOspfArea(e) {
  8425. if (e) e.preventDefault();
  8426. const payload = {
  8427. id: document.getElementById('modal-ospf-area-id').value,
  8428. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8429. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8430. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8431. area_type: document.getElementById('modal-ospf-area-type').value,
  8432. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8433. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8434. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8435. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8436. };
  8437. try {
  8438. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8439. method: 'POST',
  8440. headers: { 'Content-Type': 'application/json' },
  8441. body: JSON.stringify(payload)
  8442. });
  8443. if (res.ok) {
  8444. closeOspfAreaModal();
  8445. showToast('Saved', 'OSPF area saved', 'success');
  8446. loadDynamicRouting();
  8447. } else {
  8448. const err = await res.json();
  8449. showToast('Error', err.error || 'Failed to save area', 'error');
  8450. }
  8451. } catch (err) {
  8452. showToast('Error', err.message, 'error');
  8453. }
  8454. }
  8455. function applyOspfAreaForm() {
  8456. submitOspfArea(null);
  8457. }
  8458. function copyOspfArea() {
  8459. document.getElementById('modal-ospf-area-id').value = '';
  8460. document.getElementById('modal-ospf-area-name').value += '-copy';
  8461. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8462. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8463. }
  8464. async function deleteCurrentOspfArea() {
  8465. const id = document.getElementById('modal-ospf-area-id').value;
  8466. if (!id) return;
  8467. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8468. try {
  8469. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8470. if (res.ok) {
  8471. closeOspfAreaModal();
  8472. showToast('Removed', 'OSPF area deleted', 'success');
  8473. loadDynamicRouting();
  8474. }
  8475. } catch (err) {
  8476. showToast('Error', err.message, 'error');
  8477. }
  8478. }
  8479. async function enableSelectedOspfArea() {
  8480. const id = state.selectedOspfRow?.areas;
  8481. if (!id) return;
  8482. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8483. method: 'POST',
  8484. headers: { 'Content-Type': 'application/json' },
  8485. body: JSON.stringify({ disabled: false })
  8486. });
  8487. loadDynamicRouting();
  8488. }
  8489. async function disableSelectedOspfArea() {
  8490. const id = state.selectedOspfRow?.areas;
  8491. if (!id) return;
  8492. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8493. method: 'POST',
  8494. headers: { 'Content-Type': 'application/json' },
  8495. body: JSON.stringify({ disabled: true })
  8496. });
  8497. loadDynamicRouting();
  8498. }
  8499. async function removeSelectedOspfArea() {
  8500. const id = state.selectedOspfRow?.areas;
  8501. if (!id) return;
  8502. if (!confirm('Delete selected OSPF area?')) return;
  8503. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8504. loadDynamicRouting();
  8505. }
  8506. async function promptCommentOspfArea() {
  8507. const id = state.selectedOspfRow?.areas;
  8508. if (!id) return;
  8509. const area = (state.ospfAreas || []).find(a => a.id === id);
  8510. if (!area) return;
  8511. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8512. if (comment === null) return;
  8513. area.comment = comment;
  8514. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8515. method: 'POST',
  8516. headers: { 'Content-Type': 'application/json' },
  8517. body: JSON.stringify(area)
  8518. });
  8519. loadDynamicRouting();
  8520. }
  8521. // --- 3. OSPF AREA RANGE ---
  8522. function populateAreaRangeDropdowns() {
  8523. const select = document.getElementById('modal-ospf-range-area');
  8524. if (select) {
  8525. const cur = select.value;
  8526. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8527. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8528. if (cur) select.value = cur;
  8529. }
  8530. }
  8531. function openOspfAreaRangeModal(id = null) {
  8532. const isEdit = !!id;
  8533. populateAreaRangeDropdowns();
  8534. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8535. id: '',
  8536. area: 'Default',
  8537. prefix: '',
  8538. cost: 1,
  8539. advertise: true,
  8540. disabled: false,
  8541. comment: ''
  8542. };
  8543. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8544. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8545. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8546. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8547. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8548. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8549. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8550. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8551. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8552. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8553. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8554. }
  8555. function openEditOspfAreaRangeModal(id) {
  8556. openOspfAreaRangeModal(id);
  8557. }
  8558. function closeOspfAreaRangeModal() {
  8559. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8560. }
  8561. async function submitOspfAreaRange(e) {
  8562. if (e) e.preventDefault();
  8563. const payload = {
  8564. id: document.getElementById('modal-ospf-range-id').value,
  8565. area: document.getElementById('modal-ospf-range-area').value,
  8566. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8567. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8568. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8569. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8570. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8571. };
  8572. try {
  8573. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8574. method: 'POST',
  8575. headers: { 'Content-Type': 'application/json' },
  8576. body: JSON.stringify(payload)
  8577. });
  8578. if (res.ok) {
  8579. closeOspfAreaRangeModal();
  8580. showToast('Saved', 'Area range saved', 'success');
  8581. loadDynamicRouting();
  8582. } else {
  8583. const err = await res.json();
  8584. showToast('Error', err.error || 'Failed to save area range', 'error');
  8585. }
  8586. } catch (err) {
  8587. showToast('Error', err.message, 'error');
  8588. }
  8589. }
  8590. function applyOspfAreaRangeForm() {
  8591. submitOspfAreaRange(null);
  8592. }
  8593. async function deleteCurrentOspfAreaRange() {
  8594. const id = document.getElementById('modal-ospf-range-id').value;
  8595. if (!id) return;
  8596. if (!confirm('Delete this area range?')) return;
  8597. try {
  8598. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8599. closeOspfAreaRangeModal();
  8600. showToast('Removed', 'Area range removed', 'success');
  8601. loadDynamicRouting();
  8602. } catch (err) {
  8603. showToast('Error', err.message, 'error');
  8604. }
  8605. }
  8606. async function enableSelectedOspfAreaRange() {
  8607. const id = state.selectedOspfRow?.['area-ranges'];
  8608. if (!id) return;
  8609. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8610. if (!r) return;
  8611. r.disabled = false;
  8612. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8613. loadDynamicRouting();
  8614. }
  8615. async function disableSelectedOspfAreaRange() {
  8616. const id = state.selectedOspfRow?.['area-ranges'];
  8617. if (!id) return;
  8618. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8619. if (!r) return;
  8620. r.disabled = true;
  8621. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8622. loadDynamicRouting();
  8623. }
  8624. async function removeSelectedOspfAreaRange() {
  8625. const id = state.selectedOspfRow?.['area-ranges'];
  8626. if (!id) return;
  8627. if (!confirm('Delete selected area range?')) return;
  8628. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8629. loadDynamicRouting();
  8630. }
  8631. async function promptCommentOspfAreaRange() {
  8632. const id = state.selectedOspfRow?.['area-ranges'];
  8633. if (!id) return;
  8634. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8635. if (!r) return;
  8636. const comment = prompt('Enter comment for area range:', r.comment || '');
  8637. if (comment === null) return;
  8638. r.comment = comment;
  8639. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8640. loadDynamicRouting();
  8641. }
  8642. // --- 4. OSPF INTERFACE TEMPLATE ---
  8643. function switchOspfTemplateTab(tab) {
  8644. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8645. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8646. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8647. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8648. if (tab === 'general') {
  8649. if (tabGen) tabGen.classList.remove('hidden');
  8650. if (tabAuth) tabAuth.classList.add('hidden');
  8651. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8652. 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';
  8653. } else {
  8654. if (tabGen) tabGen.classList.add('hidden');
  8655. if (tabAuth) tabAuth.classList.remove('hidden');
  8656. 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';
  8657. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8658. }
  8659. }
  8660. function populateTemplateAreaDropdowns() {
  8661. const select = document.getElementById('modal-ospf-tmpl-area');
  8662. if (select) {
  8663. const cur = select.value;
  8664. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8665. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8666. if (cur) select.value = cur;
  8667. }
  8668. }
  8669. function openOspfTemplateModal(id = null) {
  8670. const isEdit = !!id;
  8671. populateTemplateAreaDropdowns();
  8672. switchOspfTemplateTab('general');
  8673. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8674. id: '',
  8675. interfaces: '',
  8676. area: 'Default',
  8677. networks: '',
  8678. network_type: 'broadcast',
  8679. cost: 1,
  8680. priority: 128,
  8681. passive: false,
  8682. hello_interval: 10,
  8683. dead_interval: 40,
  8684. auth: 'none',
  8685. auth_key: '',
  8686. disabled: false,
  8687. comment: ''
  8688. };
  8689. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8690. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8691. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8692. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8693. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8694. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8695. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8696. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8697. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8698. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8699. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8700. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8701. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8702. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8703. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8704. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8705. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8706. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8707. }
  8708. function openEditOspfTemplateModal(id) {
  8709. openOspfTemplateModal(id);
  8710. }
  8711. function closeOspfTemplateModal() {
  8712. document.getElementById('ospf-template-modal').classList.add('hidden');
  8713. }
  8714. async function submitOspfTemplate(e) {
  8715. if (e) e.preventDefault();
  8716. const payload = {
  8717. id: document.getElementById('modal-ospf-tmpl-id').value,
  8718. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8719. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8720. area: document.getElementById('modal-ospf-tmpl-area').value,
  8721. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8722. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8723. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8724. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8725. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8726. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8727. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8728. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8729. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8730. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8731. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8732. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8733. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8734. };
  8735. try {
  8736. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8737. method: 'POST',
  8738. headers: { 'Content-Type': 'application/json' },
  8739. body: JSON.stringify(payload)
  8740. });
  8741. if (res.ok) {
  8742. closeOspfTemplateModal();
  8743. showToast('Saved', 'Interface template saved', 'success');
  8744. loadDynamicRouting();
  8745. } else {
  8746. const err = await res.json();
  8747. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8748. }
  8749. } catch (err) {
  8750. showToast('Error', err.message, 'error');
  8751. }
  8752. }
  8753. function applyOspfTemplateForm() {
  8754. submitOspfTemplate(null);
  8755. }
  8756. function copyOspfTemplate() {
  8757. document.getElementById('modal-ospf-tmpl-id').value = '';
  8758. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8759. showToast('Copied', 'Duplicated as new template', 'info');
  8760. }
  8761. async function deleteCurrentOspfTemplate() {
  8762. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8763. if (!id) return;
  8764. if (!confirm('Delete this interface template?')) return;
  8765. try {
  8766. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8767. closeOspfTemplateModal();
  8768. showToast('Removed', 'Interface template deleted', 'success');
  8769. loadDynamicRouting();
  8770. } catch (err) {
  8771. showToast('Error', err.message, 'error');
  8772. }
  8773. }
  8774. async function enableSelectedOspfTemplate() {
  8775. const id = state.selectedOspfRow?.templates;
  8776. if (!id) return;
  8777. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8778. method: 'POST',
  8779. headers: { 'Content-Type': 'application/json' },
  8780. body: JSON.stringify({ disabled: false })
  8781. });
  8782. loadDynamicRouting();
  8783. }
  8784. async function disableSelectedOspfTemplate() {
  8785. const id = state.selectedOspfRow?.templates;
  8786. if (!id) return;
  8787. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8788. method: 'POST',
  8789. headers: { 'Content-Type': 'application/json' },
  8790. body: JSON.stringify({ disabled: true })
  8791. });
  8792. loadDynamicRouting();
  8793. }
  8794. async function removeSelectedOspfTemplate() {
  8795. const id = state.selectedOspfRow?.templates;
  8796. if (!id) return;
  8797. if (!confirm('Delete selected interface template?')) return;
  8798. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8799. loadDynamicRouting();
  8800. }
  8801. async function promptCommentOspfTemplate() {
  8802. const id = state.selectedOspfRow?.templates;
  8803. if (!id) return;
  8804. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8805. if (!tmpl) return;
  8806. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8807. if (comment === null) return;
  8808. tmpl.comment = comment;
  8809. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8810. method: 'POST',
  8811. headers: { 'Content-Type': 'application/json' },
  8812. body: JSON.stringify(tmpl)
  8813. });
  8814. loadDynamicRouting();
  8815. }
  8816. // --- 5. OSPF STATIC NEIGHBOR ---
  8817. function populateStaticNbrAreaDropdowns() {
  8818. const select = document.getElementById('modal-ospf-snbr-area');
  8819. if (select) {
  8820. const cur = select.value;
  8821. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8822. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8823. if (cur) select.value = cur;
  8824. }
  8825. }
  8826. function openOspfStaticNbrModal(id = null) {
  8827. const isEdit = !!id;
  8828. populateStaticNbrAreaDropdowns();
  8829. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8830. id: '',
  8831. address: '',
  8832. area: 'Default',
  8833. poll_interval: 120,
  8834. cost: 1,
  8835. disabled: false,
  8836. comment: ''
  8837. };
  8838. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8839. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8840. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8841. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8842. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8843. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8844. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8845. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8846. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8847. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8848. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8849. }
  8850. function openEditOspfStaticNbrModal(id) {
  8851. openOspfStaticNbrModal(id);
  8852. }
  8853. function closeOspfStaticNbrModal() {
  8854. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8855. }
  8856. async function submitOspfStaticNbr(e) {
  8857. if (e) e.preventDefault();
  8858. const payload = {
  8859. id: document.getElementById('modal-ospf-snbr-id').value,
  8860. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8861. area: document.getElementById('modal-ospf-snbr-area').value,
  8862. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8863. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8864. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8865. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8866. };
  8867. try {
  8868. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8869. method: 'POST',
  8870. headers: { 'Content-Type': 'application/json' },
  8871. body: JSON.stringify(payload)
  8872. });
  8873. if (res.ok) {
  8874. closeOspfStaticNbrModal();
  8875. showToast('Saved', 'Static neighbor saved', 'success');
  8876. loadDynamicRouting();
  8877. } else {
  8878. const err = await res.json();
  8879. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8880. }
  8881. } catch (err) {
  8882. showToast('Error', err.message, 'error');
  8883. }
  8884. }
  8885. function applyOspfStaticNbrForm() {
  8886. submitOspfStaticNbr(null);
  8887. }
  8888. async function deleteCurrentOspfStaticNbr() {
  8889. const id = document.getElementById('modal-ospf-snbr-id').value;
  8890. if (!id) return;
  8891. if (!confirm('Delete this static neighbor?')) return;
  8892. try {
  8893. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8894. closeOspfStaticNbrModal();
  8895. showToast('Removed', 'Static neighbor removed', 'success');
  8896. loadDynamicRouting();
  8897. } catch (err) {
  8898. showToast('Error', err.message, 'error');
  8899. }
  8900. }
  8901. async function enableSelectedOspfStaticNbr() {
  8902. const id = state.selectedOspfRow?.['static-nbrs'];
  8903. if (!id) return;
  8904. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8905. if (!n) return;
  8906. n.disabled = false;
  8907. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8908. loadDynamicRouting();
  8909. }
  8910. async function disableSelectedOspfStaticNbr() {
  8911. const id = state.selectedOspfRow?.['static-nbrs'];
  8912. if (!id) return;
  8913. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8914. if (!n) return;
  8915. n.disabled = true;
  8916. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8917. loadDynamicRouting();
  8918. }
  8919. async function removeSelectedOspfStaticNbr() {
  8920. const id = state.selectedOspfRow?.['static-nbrs'];
  8921. if (!id) return;
  8922. if (!confirm('Delete selected static neighbor?')) return;
  8923. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8924. loadDynamicRouting();
  8925. }
  8926. async function promptCommentOspfStaticNbr() {
  8927. const id = state.selectedOspfRow?.['static-nbrs'];
  8928. if (!id) return;
  8929. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8930. if (!n) return;
  8931. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8932. if (comment === null) return;
  8933. n.comment = comment;
  8934. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8935. loadDynamicRouting();
  8936. }
  8937. // Backward-compat aliases
  8938. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8939. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8940. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8941. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8942. function deleteOspfInterface(id) {
  8943. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8944. }
  8945. function toggleOspfInterfaceState(id, disabled) {
  8946. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8947. method: 'POST',
  8948. headers: { 'Content-Type': 'application/json' },
  8949. body: JSON.stringify({ disabled })
  8950. }).then(() => loadDynamicRouting());
  8951. }
  8952. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8953. function deleteOspfArea(id) {
  8954. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8955. }
  8956. // ============================================================================
  8957. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8958. // ============================================================================
  8959. function switchBridgeSubTab(tab) {
  8960. state.bridgeSubTab = tab;
  8961. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8962. tabs.forEach(t => {
  8963. const panel = document.getElementById(`bridge-subtab-${t}`);
  8964. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8965. if (panel) {
  8966. if (t === tab) panel.classList.remove('hidden');
  8967. else panel.classList.add('hidden');
  8968. }
  8969. if (btn) {
  8970. if (t === tab) {
  8971. 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';
  8972. } else {
  8973. 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';
  8974. }
  8975. }
  8976. });
  8977. const addBtn = document.getElementById('bridge-top-action-btn');
  8978. if (addBtn) {
  8979. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8980. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8981. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8982. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8983. }
  8984. if (tab === 'hosts') loadBridgeHosts();
  8985. setTimeout(initTableSorting, 50);
  8986. }
  8987. function openCurrentBridgeModal() {
  8988. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8989. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8990. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8991. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8992. }
  8993. async function loadBridge() {
  8994. try {
  8995. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8996. fetch(`${API_BASE}/bridge/bridges`),
  8997. fetch(`${API_BASE}/bridge/ports`),
  8998. fetch(`${API_BASE}/bridge/vlans`),
  8999. fetch(`${API_BASE}/bridge/summary`),
  9000. fetch(`${API_BASE}/vpn/eoip`),
  9001. fetch(`${API_BASE}/vlans`)
  9002. ]);
  9003. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9004. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9005. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9006. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9007. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9008. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9009. // Badges & Stats
  9010. const bBridges = document.getElementById('bridge-badge-bridges');
  9011. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9012. const bPorts = document.getElementById('bridge-badge-ports');
  9013. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9014. const bVlans = document.getElementById('bridge-badge-vlans');
  9015. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9016. const bHosts = document.getElementById('bridge-badge-hosts');
  9017. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9018. const sBr = document.getElementById('bridge-stat-bridges');
  9019. if (sBr) sBr.innerText = (state.bridges || []).length;
  9020. const sPorts = document.getElementById('bridge-stat-ports');
  9021. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9022. const sHosts = document.getElementById('bridge-stat-hosts');
  9023. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9024. renderBridges();
  9025. renderBridgePorts();
  9026. renderBridgeVLANs();
  9027. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9028. } catch (err) {
  9029. console.error('Failed to load bridge subsystem:', err);
  9030. }
  9031. }
  9032. // ----------------- Bridges -----------------
  9033. function renderBridges() {
  9034. const tbody = document.getElementById('bridge-table-body');
  9035. const empty = document.getElementById('bridge-empty-bridges');
  9036. const countBadge = document.getElementById('bridge-count-badge');
  9037. if (!tbody) return;
  9038. tbody.innerHTML = '';
  9039. const bridges = state.bridges || [];
  9040. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9041. if (bridges.length === 0) {
  9042. empty?.classList.remove('hidden');
  9043. return;
  9044. }
  9045. empty?.classList.add('hidden');
  9046. bridges.forEach((b, idx) => {
  9047. const tr = document.createElement('tr');
  9048. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9049. // Format IP addresses pill list
  9050. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9051. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9052. ipsHtml = b.ip_addresses.map(ip => `
  9053. <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">
  9054. <span>${ip}</span>
  9055. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9056. </span>
  9057. `).join(' ');
  9058. }
  9059. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9060. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9061. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9062. tr.innerHTML = `
  9063. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9064. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9065. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9066. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9067. </td>
  9068. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9069. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9070. <td class="py-2.5 px-3">
  9071. <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>
  9072. </td>
  9073. <td class="py-2.5 px-3 text-center">
  9074. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9075. </td>
  9076. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9077. <td class="py-2.5 px-3">
  9078. <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>
  9079. </td>
  9080. <td class="py-2.5 px-3">
  9081. <div class="flex items-center gap-1.5 flex-wrap">
  9082. ${ipsHtml}
  9083. <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>
  9084. </div>
  9085. </td>
  9086. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9087. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9088. </td>
  9089. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9090. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9091. <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>
  9092. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9093. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9094. </td>
  9095. `;
  9096. tbody.appendChild(tr);
  9097. });
  9098. }
  9099. function openAddBridgeModal() {
  9100. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9101. document.getElementById('bridge-modal-id').value = '';
  9102. document.getElementById('bridge-modal-name').value = 'bridge1';
  9103. document.getElementById('bridge-modal-name').disabled = false;
  9104. document.getElementById('bridge-modal-mtu').value = '1500';
  9105. document.getElementById('bridge-modal-mac').value = '';
  9106. document.getElementById('bridge-modal-stp').value = 'rstp';
  9107. document.getElementById('bridge-modal-priority').value = '32768';
  9108. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9109. document.getElementById('bridge-modal-pvid').value = '1';
  9110. document.getElementById('bridge-modal-fastforward').checked = true;
  9111. document.getElementById('bridge-modal-comment').value = '';
  9112. document.getElementById('bridge-modal-disabled').checked = false;
  9113. toggleBridgeModalVlanFiltering();
  9114. document.getElementById('bridge-modal').classList.remove('hidden');
  9115. }
  9116. function openEditBridgeModal(id) {
  9117. const b = (state.bridges || []).find(x => x.id === id);
  9118. if (!b) return;
  9119. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9120. document.getElementById('bridge-modal-id').value = b.id;
  9121. document.getElementById('bridge-modal-name').value = b.name;
  9122. document.getElementById('bridge-modal-name').disabled = true;
  9123. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9124. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9125. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9126. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9127. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9128. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9129. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9130. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9131. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9132. toggleBridgeModalVlanFiltering();
  9133. document.getElementById('bridge-modal').classList.remove('hidden');
  9134. }
  9135. function closeBridgeModal() {
  9136. document.getElementById('bridge-modal').classList.add('hidden');
  9137. }
  9138. function toggleBridgeModalVlanFiltering() {
  9139. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9140. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9141. if (pvidBox) {
  9142. if (chk) pvidBox.classList.remove('opacity-40');
  9143. else pvidBox.classList.add('opacity-40');
  9144. }
  9145. }
  9146. async function submitSaveBridge(e) {
  9147. e.preventDefault();
  9148. const id = document.getElementById('bridge-modal-id').value;
  9149. const name = document.getElementById('bridge-modal-name').value.trim();
  9150. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9151. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9152. const stp = document.getElementById('bridge-modal-stp').value;
  9153. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9154. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9155. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9156. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9157. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9158. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9159. try {
  9160. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9161. method: 'POST',
  9162. headers: { 'Content-Type': 'application/json' },
  9163. body: JSON.stringify({
  9164. id,
  9165. name,
  9166. mtu,
  9167. mac_address: mac,
  9168. stp,
  9169. priority,
  9170. vlan_filtering: vlanFiltering,
  9171. pvid,
  9172. fast_forward: fastForward,
  9173. comment,
  9174. disabled
  9175. })
  9176. });
  9177. if (res.ok) {
  9178. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9179. closeBridgeModal();
  9180. loadBridge();
  9181. fetchData(false);
  9182. } else {
  9183. const err = await res.json();
  9184. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9185. }
  9186. } catch (err) {
  9187. showToast('Error', err.message, 'error');
  9188. }
  9189. }
  9190. async function toggleBridgeState(id, disabled) {
  9191. try {
  9192. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9193. method: 'POST',
  9194. headers: { 'Content-Type': 'application/json' },
  9195. body: JSON.stringify({ disabled })
  9196. });
  9197. if (res.ok) {
  9198. loadBridge();
  9199. fetchData(false);
  9200. }
  9201. } catch (err) {
  9202. showToast('Error', err.message, 'error');
  9203. }
  9204. }
  9205. async function deleteBridge(id) {
  9206. const b = (state.bridges || []).find(x => x.id === id);
  9207. const name = b ? b.name : id;
  9208. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9209. try {
  9210. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9211. if (res.ok) {
  9212. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9213. loadBridge();
  9214. fetchData(false);
  9215. } else {
  9216. const err = await res.json();
  9217. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9218. }
  9219. } catch (err) {
  9220. showToast('Error', err.message, 'error');
  9221. }
  9222. }
  9223. // ----------------- Bridge IP Assignments -----------------
  9224. function openAddBridgeIPModal(id, name) {
  9225. document.getElementById('bridge-ip-modal-id').value = id;
  9226. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9227. document.getElementById('bridge-ip-modal-cidr').value = '';
  9228. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9229. }
  9230. function closeBridgeIPModal() {
  9231. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9232. }
  9233. async function submitAddBridgeIP(e) {
  9234. e.preventDefault();
  9235. const id = document.getElementById('bridge-ip-modal-id').value;
  9236. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9237. try {
  9238. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9239. method: 'POST',
  9240. headers: { 'Content-Type': 'application/json' },
  9241. body: JSON.stringify({ ip })
  9242. });
  9243. if (res.ok) {
  9244. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9245. closeBridgeIPModal();
  9246. loadBridge();
  9247. fetchData(false);
  9248. } else {
  9249. const err = await res.json();
  9250. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9251. }
  9252. } catch (err) {
  9253. showToast('Error', err.message, 'error');
  9254. }
  9255. }
  9256. async function deleteBridgeIP(id, ip) {
  9257. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9258. try {
  9259. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9260. method: 'DELETE',
  9261. headers: { 'Content-Type': 'application/json' },
  9262. body: JSON.stringify({ ip })
  9263. });
  9264. if (res.ok) {
  9265. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9266. loadBridge();
  9267. fetchData(false);
  9268. }
  9269. } catch (err) {
  9270. showToast('Error', err.message, 'error');
  9271. }
  9272. }
  9273. // ----------------- Bridge Ports -----------------
  9274. function renderBridgePorts() {
  9275. const tbody = document.getElementById('bridge-ports-table-body');
  9276. const empty = document.getElementById('bridge-empty-ports');
  9277. const countBadge = document.getElementById('bridge-ports-count-badge');
  9278. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9279. if (!tbody) return;
  9280. tbody.innerHTML = '';
  9281. // Update filter select
  9282. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9283. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9284. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9285. if (ports.length === 0) {
  9286. empty?.classList.remove('hidden');
  9287. return;
  9288. }
  9289. empty?.classList.add('hidden');
  9290. ports.forEach((p, idx) => {
  9291. const tr = document.createElement('tr');
  9292. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9293. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9294. tr.innerHTML = `
  9295. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9296. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9297. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9298. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9299. </td>
  9300. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9301. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9302. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9303. <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>
  9304. <td class="py-2.5 px-3">
  9305. ${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>'}
  9306. </td>
  9307. <td class="py-2.5 px-3">
  9308. <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>
  9309. </td>
  9310. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9311. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9312. <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>
  9313. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9314. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9315. </td>
  9316. `;
  9317. tbody.appendChild(tr);
  9318. });
  9319. }
  9320. function openAddBridgePortModal() {
  9321. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9322. document.getElementById('bridge-port-modal-id').value = '';
  9323. populateBridgeSelect('bridge-port-modal-bridge');
  9324. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9325. document.getElementById('bridge-port-modal-pvid').value = '1';
  9326. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9327. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9328. document.getElementById('bridge-port-modal-horizon').value = '0';
  9329. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9330. document.getElementById('bridge-port-modal-priority').value = '128';
  9331. document.getElementById('bridge-port-modal-learn').checked = true;
  9332. document.getElementById('bridge-port-modal-comment').value = '';
  9333. document.getElementById('bridge-port-modal-disabled').checked = false;
  9334. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9335. }
  9336. function openEditBridgePortModal(id) {
  9337. const p = (state.bridgePorts || []).find(x => x.id === id);
  9338. if (!p) return;
  9339. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9340. document.getElementById('bridge-port-modal-id').value = p.id;
  9341. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9342. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9343. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9344. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9345. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9346. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9347. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9348. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9349. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9350. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9351. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9352. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9353. }
  9354. function closeBridgePortModal() {
  9355. document.getElementById('bridge-port-modal').classList.add('hidden');
  9356. }
  9357. async function submitSaveBridgePort(e) {
  9358. e.preventDefault();
  9359. const id = document.getElementById('bridge-port-modal-id').value;
  9360. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9361. const iface = document.getElementById('bridge-port-modal-interface').value;
  9362. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9363. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9364. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9365. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9366. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9367. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9368. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9369. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9370. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9371. try {
  9372. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9373. method: 'POST',
  9374. headers: { 'Content-Type': 'application/json' },
  9375. body: JSON.stringify({
  9376. id,
  9377. bridge,
  9378. interface: iface,
  9379. pvid,
  9380. frame_types: frameTypes,
  9381. ingress_filtering: ingressFiltering,
  9382. horizon,
  9383. path_cost: pathCost,
  9384. priority,
  9385. learn,
  9386. comment,
  9387. disabled
  9388. })
  9389. });
  9390. if (res.ok) {
  9391. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9392. closeBridgePortModal();
  9393. loadBridge();
  9394. fetchData(false);
  9395. } else {
  9396. const err = await res.json();
  9397. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9398. }
  9399. } catch (err) {
  9400. showToast('Error', err.message, 'error');
  9401. }
  9402. }
  9403. async function toggleBridgePortState(id, disabled) {
  9404. try {
  9405. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9406. method: 'POST',
  9407. headers: { 'Content-Type': 'application/json' },
  9408. body: JSON.stringify({ disabled })
  9409. });
  9410. if (res.ok) {
  9411. loadBridge();
  9412. fetchData(false);
  9413. }
  9414. } catch (err) {
  9415. showToast('Error', err.message, 'error');
  9416. }
  9417. }
  9418. async function deleteBridgePort(id) {
  9419. const p = (state.bridgePorts || []).find(x => x.id === id);
  9420. const iface = p ? p.interface : id;
  9421. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9422. try {
  9423. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9424. if (res.ok) {
  9425. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9426. loadBridge();
  9427. fetchData(false);
  9428. }
  9429. } catch (err) {
  9430. showToast('Error', err.message, 'error');
  9431. }
  9432. }
  9433. // ----------------- Bridge VLANs -----------------
  9434. function renderBridgeVLANs() {
  9435. const tbody = document.getElementById('bridge-vlans-table-body');
  9436. const empty = document.getElementById('bridge-empty-vlans');
  9437. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9438. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9439. if (!tbody) return;
  9440. tbody.innerHTML = '';
  9441. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9442. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9443. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9444. if (vlans.length === 0) {
  9445. empty?.classList.remove('hidden');
  9446. return;
  9447. }
  9448. empty?.classList.add('hidden');
  9449. vlans.forEach((v, idx) => {
  9450. const tr = document.createElement('tr');
  9451. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9452. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9453. ? 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(' ')
  9454. : '<span class="text-slate-600">none</span>';
  9455. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9456. ? 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(' ')
  9457. : '<span class="text-slate-600">none</span>';
  9458. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9459. tr.innerHTML = `
  9460. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9461. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9462. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9463. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9464. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9465. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9466. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9467. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9468. <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>
  9469. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9470. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9471. </td>
  9472. `;
  9473. tbody.appendChild(tr);
  9474. });
  9475. }
  9476. function openAddBridgeVLANModal() {
  9477. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9478. document.getElementById('bridge-vlan-modal-id').value = '';
  9479. populateBridgeSelect('bridge-vlan-modal-bridge');
  9480. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9481. document.getElementById('bridge-vlan-modal-comment').value = '';
  9482. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9483. updateBridgeVlanPortCheckboxes();
  9484. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9485. }
  9486. function openEditBridgeVLANModal(id) {
  9487. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9488. if (!v) return;
  9489. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9490. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9491. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9492. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9493. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9494. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9495. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9496. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9497. }
  9498. function closeBridgeVlanModal() {
  9499. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9500. }
  9501. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9502. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9503. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9504. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9505. if (!taggedBox || !untaggedBox) return;
  9506. // Ports belonging to the selected bridge
  9507. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9508. if (memberPorts.length === 0) {
  9509. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9510. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9511. return;
  9512. }
  9513. taggedBox.innerHTML = memberPorts.map(p => `
  9514. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9515. <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">
  9516. <span>${p.interface}</span>
  9517. </label>
  9518. `).join('');
  9519. untaggedBox.innerHTML = memberPorts.map(p => `
  9520. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9521. <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">
  9522. <span>${p.interface}</span>
  9523. </label>
  9524. `).join('');
  9525. }
  9526. async function submitSaveBridgeVLAN(e) {
  9527. e.preventDefault();
  9528. const id = document.getElementById('bridge-vlan-modal-id').value;
  9529. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9530. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9531. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9532. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9533. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9534. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9535. try {
  9536. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9537. method: 'POST',
  9538. headers: { 'Content-Type': 'application/json' },
  9539. body: JSON.stringify({
  9540. id,
  9541. bridge,
  9542. vlan_ids: vlanIDs,
  9543. tagged,
  9544. untagged,
  9545. comment,
  9546. disabled
  9547. })
  9548. });
  9549. if (res.ok) {
  9550. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9551. closeBridgeVlanModal();
  9552. loadBridge();
  9553. } else {
  9554. const err = await res.json();
  9555. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9556. }
  9557. } catch (err) {
  9558. showToast('Error', err.message, 'error');
  9559. }
  9560. }
  9561. async function toggleBridgeVLANState(id, disabled) {
  9562. try {
  9563. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9564. method: 'POST',
  9565. headers: { 'Content-Type': 'application/json' },
  9566. body: JSON.stringify({ disabled })
  9567. });
  9568. if (res.ok) loadBridge();
  9569. } catch (err) {
  9570. showToast('Error', err.message, 'error');
  9571. }
  9572. }
  9573. async function deleteBridgeVLAN(id) {
  9574. if (!confirm('Delete this bridge VLAN entry?')) return;
  9575. try {
  9576. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9577. if (res.ok) {
  9578. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9579. loadBridge();
  9580. }
  9581. } catch (err) {
  9582. showToast('Error', err.message, 'error');
  9583. }
  9584. }
  9585. // ----------------- Hosts / MAC Table -----------------
  9586. async function loadBridgeHosts() {
  9587. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9588. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9589. try {
  9590. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9591. const res = await fetch(url);
  9592. if (res.ok) {
  9593. state.bridgeHosts = await res.json();
  9594. renderBridgeHosts();
  9595. }
  9596. } catch (err) {
  9597. console.error('Failed to load bridge hosts:', err);
  9598. }
  9599. }
  9600. function renderBridgeHosts() {
  9601. const tbody = document.getElementById('bridge-hosts-table-body');
  9602. const empty = document.getElementById('bridge-empty-hosts');
  9603. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9604. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9605. if (!tbody) return;
  9606. tbody.innerHTML = '';
  9607. const hosts = (state.bridgeHosts || []).filter(h => {
  9608. if (!search) return true;
  9609. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9610. });
  9611. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9612. if (hosts.length === 0) {
  9613. empty?.classList.remove('hidden');
  9614. return;
  9615. }
  9616. empty?.classList.add('hidden');
  9617. hosts.forEach(h => {
  9618. const tr = document.createElement('tr');
  9619. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9620. let flagBadges = '';
  9621. 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>';
  9622. 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>';
  9623. 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>';
  9624. tr.innerHTML = `
  9625. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9626. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9627. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9628. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9629. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9630. <td class="py-2.5 px-3">${flagBadges}</td>
  9631. `;
  9632. tbody.appendChild(tr);
  9633. });
  9634. }
  9635. async function flushBridgeHosts() {
  9636. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9637. if (!selBridge) {
  9638. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9639. return;
  9640. }
  9641. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9642. try {
  9643. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9644. method: 'POST',
  9645. headers: { 'Content-Type': 'application/json' },
  9646. body: JSON.stringify({ bridge: selBridge })
  9647. });
  9648. if (res.ok) {
  9649. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9650. loadBridgeHosts();
  9651. }
  9652. } catch (err) {
  9653. showToast('Error', err.message, 'error');
  9654. }
  9655. }
  9656. // ----------------- Helpers -----------------
  9657. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9658. const sel = document.getElementById(selectId);
  9659. if (!sel) return;
  9660. const prevVal = currentVal || sel.value;
  9661. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9662. (state.bridges || []).forEach(b => {
  9663. const opt = document.createElement('option');
  9664. opt.value = b.name;
  9665. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9666. if (b.name === prevVal) opt.selected = true;
  9667. sel.appendChild(opt);
  9668. });
  9669. }
  9670. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9671. const sel = document.getElementById(selectId);
  9672. if (!sel) return;
  9673. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9674. // 1. Physical Interfaces
  9675. const grpPhys = document.createElement('optgroup');
  9676. grpPhys.label = 'Physical Interfaces';
  9677. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9678. const opt = document.createElement('option');
  9679. opt.value = i.name;
  9680. opt.innerText = `${i.name} (${i.role || i.type})`;
  9681. if (i.name === currentVal) opt.selected = true;
  9682. grpPhys.appendChild(opt);
  9683. });
  9684. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9685. // 2. VLAN Sub-interfaces
  9686. const grpVlans = document.createElement('optgroup');
  9687. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9688. (state.vlans || []).forEach(v => {
  9689. const opt = document.createElement('option');
  9690. opt.value = v.name;
  9691. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9692. if (v.name === currentVal) opt.selected = true;
  9693. grpVlans.appendChild(opt);
  9694. });
  9695. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9696. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9697. const grpEoip = document.createElement('optgroup');
  9698. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9699. (state.eoipTunnels || []).forEach(t => {
  9700. const opt = document.createElement('option');
  9701. opt.value = t.name;
  9702. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9703. if (t.name === currentVal) opt.selected = true;
  9704. grpEoip.appendChild(opt);
  9705. });
  9706. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9707. }
  9708. // -------------------------------------------------------------
  9709. // RouterOS v7 Routing Filters Management (/routing filter)
  9710. // -------------------------------------------------------------
  9711. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9712. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9713. if (!state.rfSort) state.rfSort = {};
  9714. function switchRoutingFilterTab(tab) {
  9715. state.activeRoutingFilterTab = tab;
  9716. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9717. tabs.forEach(t => {
  9718. const btn = document.getElementById(`tab-rf-${t}`);
  9719. const content = document.getElementById(`tab-content-rf-${t}`);
  9720. if (btn) {
  9721. if (t === tab) {
  9722. 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';
  9723. } else {
  9724. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9725. }
  9726. }
  9727. if (content) {
  9728. if (t === tab) content.classList.remove('hidden');
  9729. else content.classList.add('hidden');
  9730. }
  9731. });
  9732. const chainContainer = document.getElementById('rf-chain-filter-container');
  9733. if (chainContainer) {
  9734. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9735. else chainContainer.classList.add('hidden');
  9736. }
  9737. renderRoutingFilters();
  9738. }
  9739. function selectFilterRow(tab, id) {
  9740. if (state.selectedFilterRow[tab] === id) {
  9741. delete state.selectedFilterRow[tab];
  9742. } else {
  9743. state.selectedFilterRow[tab] = id;
  9744. }
  9745. if (tab === 'rules') renderRoutingFilterRules();
  9746. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9747. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9748. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9749. }
  9750. function openRoutingFilterNewModal() {
  9751. const tab = state.activeRoutingFilterTab || 'rules';
  9752. if (tab === 'rules') openAddRoutingFilterModal();
  9753. else if (tab === 'select-rules') openAddSelectRuleModal();
  9754. else if (tab === 'community-lists') openAddCommunityListModal();
  9755. else if (tab === 'as-lists') openAddASListModal();
  9756. }
  9757. function toggleSelectedRoutingFilter(disabled) {
  9758. const tab = state.activeRoutingFilterTab || 'rules';
  9759. const id = state.selectedFilterRow[tab];
  9760. if (!id) {
  9761. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9762. return;
  9763. }
  9764. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9765. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9766. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9767. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9768. }
  9769. function removeSelectedRoutingFilter() {
  9770. const tab = state.activeRoutingFilterTab || 'rules';
  9771. const id = state.selectedFilterRow[tab];
  9772. if (!id) {
  9773. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9774. return;
  9775. }
  9776. if (tab === 'rules') deleteRoutingFilter(id);
  9777. else if (tab === 'select-rules') deleteSelectRule(id);
  9778. else if (tab === 'community-lists') deleteCommunityList(id);
  9779. else if (tab === 'as-lists') deleteASList(id);
  9780. }
  9781. function searchRoutingFilters(q) {
  9782. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9783. renderRoutingFilters();
  9784. }
  9785. function sortFilterTable(tab, col) {
  9786. if (!state.rfSort) state.rfSort = {};
  9787. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9788. if (state.rfSort[tab].col === col) {
  9789. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9790. } else {
  9791. state.rfSort[tab].col = col;
  9792. state.rfSort[tab].asc = true;
  9793. }
  9794. const asc = state.rfSort[tab].asc;
  9795. let list = [];
  9796. if (tab === 'rules') list = state.routingFilters || [];
  9797. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9798. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9799. else if (tab === 'as-lists') list = state.routingASLists || [];
  9800. list.sort((a, b) => {
  9801. let valA = a[col] ?? '';
  9802. let valB = b[col] ?? '';
  9803. if (col === 'flags') {
  9804. valA = a.disabled ? 'X' : 'A';
  9805. valB = b.disabled ? 'X' : 'A';
  9806. }
  9807. if (typeof valA === 'number' && typeof valB === 'number') {
  9808. return asc ? valA - valB : valB - valA;
  9809. }
  9810. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9811. });
  9812. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9813. allCols.forEach(c => {
  9814. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9815. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9816. });
  9817. if (tab === 'rules') renderRoutingFilterRules();
  9818. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9819. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9820. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9821. }
  9822. function renderRoutingFilters() {
  9823. const navBadge = document.getElementById('badge-filters-count');
  9824. const allRules = state.routingFilters || [];
  9825. if (navBadge) navBadge.innerText = allRules.length;
  9826. // Populate chain filter select options and datalist
  9827. const chainSelect = document.getElementById('routing-filter-chain-select');
  9828. const chainDatalist = document.getElementById('dl-routing-chains');
  9829. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9830. if (chainSelect) {
  9831. const currentVal = state.filterChainSelected || 'all';
  9832. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9833. uniqueChains.map(ch => {
  9834. const count = allRules.filter(r => r.chain === ch).length;
  9835. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9836. }).join('');
  9837. chainSelect.value = currentVal;
  9838. }
  9839. if (chainDatalist) {
  9840. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9841. }
  9842. renderRoutingFilterRules();
  9843. renderRoutingFilterSelectRules();
  9844. renderRoutingFilterCommunityLists();
  9845. renderRoutingFilterASLists();
  9846. }
  9847. function filterRoutingFiltersByChain(chain) {
  9848. state.filterChainSelected = chain;
  9849. renderRoutingFilters();
  9850. }
  9851. // -------------------------------------------------------------
  9852. // TAB 1: RULES (/routing filter rule)
  9853. // -------------------------------------------------------------
  9854. function renderRoutingFilterRules() {
  9855. const tbody = document.getElementById('routing-filter-rules-tbody');
  9856. if (!tbody) return;
  9857. const empty = document.getElementById('rf-rules-empty');
  9858. const statusCount = document.getElementById('rf-status-count');
  9859. let list = (state.routingFilters || []).slice();
  9860. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9861. list = list.filter(r => r.chain === state.filterChainSelected);
  9862. }
  9863. const q = state.rfSearchQuery;
  9864. if (q) {
  9865. list = list.filter(r =>
  9866. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9867. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9868. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9869. (r.comment && r.comment.toLowerCase().includes(q))
  9870. );
  9871. }
  9872. if (!state.rfSort?.['rules']) {
  9873. list.sort((a, b) => {
  9874. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9875. return (a.rule_order || 0) - (b.rule_order || 0);
  9876. });
  9877. }
  9878. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9879. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9880. }
  9881. if (list.length === 0) {
  9882. tbody.innerHTML = '';
  9883. if (empty) empty.classList.remove('hidden');
  9884. return;
  9885. }
  9886. if (empty) empty.classList.add('hidden');
  9887. tbody.innerHTML = list.map(r => {
  9888. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9889. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9890. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9891. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9892. let ruleDisplay = '';
  9893. if (r.rule && r.rule.trim() !== '') {
  9894. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9895. } else {
  9896. let conds = [];
  9897. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9898. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9899. let act = r.action || 'accept';
  9900. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9901. }
  9902. return `
  9903. <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'}">
  9904. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9905. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9906. <td class="py-2 px-3">
  9907. <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>
  9908. </td>
  9909. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9910. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9911. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9912. <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>
  9913. <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>
  9914. <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'}">
  9915. ${r.disabled ? 'Enable' : 'Disable'}
  9916. </button>
  9917. <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">
  9918. Edit
  9919. </button>
  9920. <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">
  9921. ✕
  9922. </button>
  9923. </td>
  9924. </tr>
  9925. `;
  9926. }).join('');
  9927. }
  9928. // -------------------------------------------------------------
  9929. // TAB 2: SELECT RULES (/routing filter select-rule)
  9930. // -------------------------------------------------------------
  9931. function renderRoutingFilterSelectRules() {
  9932. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9933. if (!tbody) return;
  9934. const empty = document.getElementById('rf-select-rules-empty');
  9935. const statusCount = document.getElementById('rf-status-count');
  9936. let list = (state.routingSelectRules || []).slice();
  9937. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9938. list = list.filter(r => r.chain === state.filterChainSelected);
  9939. }
  9940. const q = state.rfSearchQuery;
  9941. if (q) {
  9942. list = list.filter(r =>
  9943. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9944. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9945. (r.comment && r.comment.toLowerCase().includes(q))
  9946. );
  9947. }
  9948. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9949. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9950. }
  9951. if (list.length === 0) {
  9952. tbody.innerHTML = '';
  9953. if (empty) empty.classList.remove('hidden');
  9954. return;
  9955. }
  9956. if (empty) empty.classList.add('hidden');
  9957. tbody.innerHTML = list.map(r => {
  9958. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9959. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9960. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9961. return `
  9962. <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'}">
  9963. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9964. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9965. <td class="py-2 px-3">
  9966. <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>
  9967. </td>
  9968. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9969. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9970. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9971. <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'}">
  9972. ${r.disabled ? 'Enable' : 'Disable'}
  9973. </button>
  9974. <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">
  9975. Edit
  9976. </button>
  9977. <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">
  9978. ✕
  9979. </button>
  9980. </td>
  9981. </tr>
  9982. `;
  9983. }).join('');
  9984. }
  9985. // -------------------------------------------------------------
  9986. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9987. // -------------------------------------------------------------
  9988. function renderRoutingFilterCommunityLists() {
  9989. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9990. if (!tbody) return;
  9991. const empty = document.getElementById('rf-comm-lists-empty');
  9992. const statusCount = document.getElementById('rf-status-count');
  9993. let list = (state.routingCommunityLists || []).slice();
  9994. const q = state.rfSearchQuery;
  9995. if (q) {
  9996. list = list.filter(cl =>
  9997. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9998. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9999. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10000. );
  10001. }
  10002. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10003. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10004. }
  10005. if (list.length === 0) {
  10006. tbody.innerHTML = '';
  10007. if (empty) empty.classList.remove('hidden');
  10008. return;
  10009. }
  10010. if (empty) empty.classList.add('hidden');
  10011. tbody.innerHTML = list.map(cl => {
  10012. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10013. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10014. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10015. const commBadges = (cl.communities || []).map(c =>
  10016. `<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>`
  10017. ).join(' ');
  10018. return `
  10019. <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'}">
  10020. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10021. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10022. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10023. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10024. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10025. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10026. <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'}">
  10027. ${cl.disabled ? 'Enable' : 'Disable'}
  10028. </button>
  10029. <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">
  10030. Edit
  10031. </button>
  10032. <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">
  10033. ✕
  10034. </button>
  10035. </td>
  10036. </tr>
  10037. `;
  10038. }).join('');
  10039. }
  10040. // -------------------------------------------------------------
  10041. // TAB 4: AS LISTS (/routing filter num-list)
  10042. // -------------------------------------------------------------
  10043. function renderRoutingFilterASLists() {
  10044. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10045. if (!tbody) return;
  10046. const empty = document.getElementById('rf-as-lists-empty');
  10047. const statusCount = document.getElementById('rf-status-count');
  10048. let list = (state.routingASLists || []).slice();
  10049. const q = state.rfSearchQuery;
  10050. if (q) {
  10051. list = list.filter(al =>
  10052. (al.name && al.name.toLowerCase().includes(q)) ||
  10053. (al.range && al.range.toLowerCase().includes(q)) ||
  10054. (al.comment && al.comment.toLowerCase().includes(q))
  10055. );
  10056. }
  10057. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10058. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10059. }
  10060. if (list.length === 0) {
  10061. tbody.innerHTML = '';
  10062. if (empty) empty.classList.remove('hidden');
  10063. return;
  10064. }
  10065. if (empty) empty.classList.add('hidden');
  10066. tbody.innerHTML = list.map(al => {
  10067. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10068. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10069. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10070. return `
  10071. <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'}">
  10072. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10073. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10074. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10075. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10076. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10077. <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'}">
  10078. ${al.disabled ? 'Enable' : 'Disable'}
  10079. </button>
  10080. <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">
  10081. Edit
  10082. </button>
  10083. <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">
  10084. ✕
  10085. </button>
  10086. </td>
  10087. </tr>
  10088. `;
  10089. }).join('');
  10090. }
  10091. // -------------------------------------------------------------
  10092. // SNIPPETS & WIZARD HELPERS
  10093. // -------------------------------------------------------------
  10094. function insertRuleSnippet(type) {
  10095. const textarea = document.getElementById('modal-rf-rule');
  10096. if (!textarea) return;
  10097. let snippet = '';
  10098. switch (type) {
  10099. case 'accept-default':
  10100. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10101. break;
  10102. case 'drop-rfc1918':
  10103. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10104. break;
  10105. case 'len-24':
  10106. snippet = 'if (dst-len > 24) { reject; }';
  10107. break;
  10108. case 'local-pref-150':
  10109. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10110. break;
  10111. case 'as-prepend-2':
  10112. snippet = 'set bgp-path-prepend 2; accept;';
  10113. break;
  10114. case 'set-comm':
  10115. snippet = 'set bgp-communities.add 65000:100; accept;';
  10116. break;
  10117. case 'match-comm':
  10118. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10119. break;
  10120. case 'reject-all':
  10121. snippet = 'reject;';
  10122. break;
  10123. }
  10124. if (!snippet) return;
  10125. if (!textarea.value.trim()) {
  10126. textarea.value = snippet;
  10127. } else {
  10128. textarea.value = textarea.value.trim() + '\n' + snippet;
  10129. }
  10130. }
  10131. function generateScriptFromWizard() {
  10132. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10133. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10134. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10135. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10136. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10137. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10138. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10139. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10140. const conds = [];
  10141. if (pfx) {
  10142. if (pfxLen) {
  10143. if (pfxLen.includes('-')) {
  10144. const parts = pfxLen.split('-');
  10145. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10146. } else {
  10147. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10148. }
  10149. } else {
  10150. conds.push(`dst in ${pfx}`);
  10151. }
  10152. }
  10153. if (proto && proto !== 'any') {
  10154. conds.push(`protocol ${proto}`);
  10155. }
  10156. if (asp) {
  10157. conds.push(`bgp-as-path "${asp}"`);
  10158. }
  10159. if (comm) {
  10160. conds.push(`bgp-communities includes ${comm}`);
  10161. }
  10162. const actions = [];
  10163. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10164. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10165. actions.push(`${act};`);
  10166. let code = '';
  10167. if (conds.length > 0) {
  10168. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10169. } else {
  10170. code = actions.join(' ');
  10171. }
  10172. const textarea = document.getElementById('modal-rf-rule');
  10173. if (textarea) textarea.value = code;
  10174. }
  10175. // -------------------------------------------------------------
  10176. // MODAL CRUD: RULES (/routing filter rule)
  10177. // -------------------------------------------------------------
  10178. function openAddRoutingFilterModal(defaultChain = '') {
  10179. const form = document.getElementById('routing-filter-form');
  10180. if (form) form.reset();
  10181. const idEl = document.getElementById('modal-rf-id');
  10182. if (idEl) idEl.value = '';
  10183. const titleEl = document.getElementById('modal-rf-title');
  10184. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10185. const chainEl = document.getElementById('modal-rf-chain');
  10186. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10187. const orderEl = document.getElementById('modal-rf-order');
  10188. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10189. const ruleEl = document.getElementById('modal-rf-rule');
  10190. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10191. const disEl = document.getElementById('modal-rf-disabled');
  10192. if (disEl) disEl.checked = false;
  10193. const modal = document.getElementById('modal-routing-filter');
  10194. if (modal) modal.classList.remove('hidden');
  10195. }
  10196. function openEditRoutingFilterModal(id) {
  10197. const r = (state.routingFilters || []).find(item => item.id === id);
  10198. if (!r) return;
  10199. const idEl = document.getElementById('modal-rf-id');
  10200. if (idEl) idEl.value = r.id;
  10201. const titleEl = document.getElementById('modal-rf-title');
  10202. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10203. const chainEl = document.getElementById('modal-rf-chain');
  10204. if (chainEl) chainEl.value = r.chain || '';
  10205. const orderEl = document.getElementById('modal-rf-order');
  10206. if (orderEl) orderEl.value = r.rule_order || 10;
  10207. const ruleEl = document.getElementById('modal-rf-rule');
  10208. if (ruleEl) {
  10209. if (r.rule) {
  10210. ruleEl.value = r.rule;
  10211. } else {
  10212. let conds = [];
  10213. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10214. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10215. let act = r.action || 'accept';
  10216. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10217. }
  10218. }
  10219. const comEl = document.getElementById('modal-rf-comment');
  10220. if (comEl) comEl.value = r.comment || '';
  10221. const disEl = document.getElementById('modal-rf-disabled');
  10222. if (disEl) disEl.checked = !!r.disabled;
  10223. const modal = document.getElementById('modal-routing-filter');
  10224. if (modal) modal.classList.remove('hidden');
  10225. }
  10226. function closeRoutingFilterModal() {
  10227. const modal = document.getElementById('modal-routing-filter');
  10228. if (modal) modal.classList.add('hidden');
  10229. }
  10230. async function submitRoutingFilter(e) {
  10231. if (e) e.preventDefault();
  10232. const payload = {
  10233. id: document.getElementById('modal-rf-id').value,
  10234. chain: document.getElementById('modal-rf-chain').value.trim(),
  10235. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10236. rule: document.getElementById('modal-rf-rule').value.trim(),
  10237. comment: document.getElementById('modal-rf-comment').value.trim(),
  10238. disabled: document.getElementById('modal-rf-disabled').checked
  10239. };
  10240. try {
  10241. const res = await fetch(`${API_BASE}/routing/filters`, {
  10242. method: 'POST',
  10243. headers: { 'Content-Type': 'application/json' },
  10244. body: JSON.stringify(payload)
  10245. });
  10246. if (res.ok) {
  10247. closeRoutingFilterModal();
  10248. showToast('Success', 'Routing filter rule saved', 'success');
  10249. loadDynamicRouting();
  10250. } else {
  10251. const err = await res.json();
  10252. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10253. }
  10254. } catch (err) {
  10255. showToast('Error', err.message, 'error');
  10256. }
  10257. }
  10258. async function applyRoutingFilterForm() {
  10259. const payload = {
  10260. id: document.getElementById('modal-rf-id').value,
  10261. chain: document.getElementById('modal-rf-chain').value.trim(),
  10262. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10263. rule: document.getElementById('modal-rf-rule').value.trim(),
  10264. comment: document.getElementById('modal-rf-comment').value.trim(),
  10265. disabled: document.getElementById('modal-rf-disabled').checked
  10266. };
  10267. try {
  10268. const res = await fetch(`${API_BASE}/routing/filters`, {
  10269. method: 'POST',
  10270. headers: { 'Content-Type': 'application/json' },
  10271. body: JSON.stringify(payload)
  10272. });
  10273. if (res.ok) {
  10274. const data = await res.json();
  10275. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10276. showToast('Applied', 'Routing filter configuration applied', 'success');
  10277. loadDynamicRouting();
  10278. } else {
  10279. const err = await res.json();
  10280. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10281. }
  10282. } catch (err) {
  10283. showToast('Error', err.message, 'error');
  10284. }
  10285. }
  10286. async function moveRoutingFilterOrder(id, delta) {
  10287. const list = state.routingFilters || [];
  10288. const idx = list.findIndex(r => r.id === id);
  10289. if (idx < 0) return;
  10290. const targetIdx = idx + delta;
  10291. if (targetIdx < 0 || targetIdx >= list.length) return;
  10292. const currentOrder = list[idx].rule_order || 10;
  10293. const targetOrder = list[targetIdx].rule_order || 20;
  10294. list[idx].rule_order = targetOrder;
  10295. list[targetIdx].rule_order = currentOrder;
  10296. try {
  10297. await fetch(`${API_BASE}/routing/filters`, {
  10298. method: 'POST',
  10299. headers: { 'Content-Type': 'application/json' },
  10300. body: JSON.stringify(list[idx])
  10301. });
  10302. await fetch(`${API_BASE}/routing/filters`, {
  10303. method: 'POST',
  10304. headers: { 'Content-Type': 'application/json' },
  10305. body: JSON.stringify(list[targetIdx])
  10306. });
  10307. loadDynamicRouting();
  10308. } catch (e) {
  10309. console.error('Reorder error:', e);
  10310. }
  10311. }
  10312. async function deleteRoutingFilter(id) {
  10313. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10314. try {
  10315. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10316. if (res.ok) {
  10317. showToast('Deleted', 'Routing filter rule removed', 'info');
  10318. loadDynamicRouting();
  10319. } else {
  10320. const err = await res.json();
  10321. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10322. }
  10323. } catch (err) {
  10324. showToast('Error', err.message, 'error');
  10325. }
  10326. }
  10327. async function toggleRoutingFilterState(id, disabled) {
  10328. try {
  10329. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10330. method: 'POST',
  10331. headers: { 'Content-Type': 'application/json' },
  10332. body: JSON.stringify({ disabled })
  10333. });
  10334. if (res.ok) {
  10335. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10336. loadDynamicRouting();
  10337. } else {
  10338. const err = await res.json();
  10339. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10340. }
  10341. } catch (err) {
  10342. showToast('Error', err.message, 'error');
  10343. }
  10344. }
  10345. // -------------------------------------------------------------
  10346. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10347. // -------------------------------------------------------------
  10348. function openAddSelectRuleModal() {
  10349. document.getElementById('modal-rf-sr-id').value = '';
  10350. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10351. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10352. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10353. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10354. document.getElementById('modal-rf-sr-comment').value = '';
  10355. document.getElementById('modal-rf-sr-disabled').checked = false;
  10356. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10357. }
  10358. function openEditSelectRuleModal(id) {
  10359. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10360. if (!r) return;
  10361. document.getElementById('modal-rf-sr-id').value = r.id;
  10362. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10363. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10364. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10365. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10366. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10367. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10368. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10369. }
  10370. function closeSelectRuleModal() {
  10371. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10372. }
  10373. async function submitSelectRule(e) {
  10374. e.preventDefault();
  10375. const payload = {
  10376. id: document.getElementById('modal-rf-sr-id').value,
  10377. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10378. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10379. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10380. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10381. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10382. };
  10383. try {
  10384. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10385. method: 'POST',
  10386. headers: { 'Content-Type': 'application/json' },
  10387. body: JSON.stringify(payload)
  10388. });
  10389. if (res.ok) {
  10390. closeSelectRuleModal();
  10391. showToast('Success', 'Select rule saved', 'success');
  10392. loadDynamicRouting();
  10393. } else {
  10394. const err = await res.json();
  10395. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10396. }
  10397. } catch (err) {
  10398. showToast('Error', err.message, 'error');
  10399. }
  10400. }
  10401. async function deleteSelectRule(id) {
  10402. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10403. try {
  10404. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10405. if (res.ok) {
  10406. showToast('Deleted', 'Select rule removed', 'info');
  10407. loadDynamicRouting();
  10408. } else {
  10409. const err = await res.json();
  10410. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10411. }
  10412. } catch (err) {
  10413. showToast('Error', err.message, 'error');
  10414. }
  10415. }
  10416. async function toggleSelectRuleState(id, disabled) {
  10417. try {
  10418. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10419. method: 'POST',
  10420. headers: { 'Content-Type': 'application/json' },
  10421. body: JSON.stringify({ disabled })
  10422. });
  10423. if (res.ok) {
  10424. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10425. loadDynamicRouting();
  10426. } else {
  10427. const err = await res.json();
  10428. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10429. }
  10430. } catch (err) {
  10431. showToast('Error', err.message, 'error');
  10432. }
  10433. }
  10434. // -------------------------------------------------------------
  10435. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10436. // -------------------------------------------------------------
  10437. function openAddCommunityListModal() {
  10438. document.getElementById('modal-rf-cl-id').value = '';
  10439. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10440. document.getElementById('modal-rf-cl-name').value = '';
  10441. document.getElementById('modal-rf-cl-communities').value = '';
  10442. document.getElementById('modal-rf-cl-regexp').value = '';
  10443. document.getElementById('modal-rf-cl-comment').value = '';
  10444. document.getElementById('modal-rf-cl-disabled').checked = false;
  10445. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10446. }
  10447. function openEditCommunityListModal(id) {
  10448. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10449. if (!cl) return;
  10450. document.getElementById('modal-rf-cl-id').value = cl.id;
  10451. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10452. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10453. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10454. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10455. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10456. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10457. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10458. }
  10459. function closeCommunityListModal() {
  10460. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10461. }
  10462. async function submitCommunityList(e) {
  10463. e.preventDefault();
  10464. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10465. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10466. const payload = {
  10467. id: document.getElementById('modal-rf-cl-id').value,
  10468. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10469. communities: comms,
  10470. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10471. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10472. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10473. };
  10474. try {
  10475. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10476. method: 'POST',
  10477. headers: { 'Content-Type': 'application/json' },
  10478. body: JSON.stringify(payload)
  10479. });
  10480. if (res.ok) {
  10481. closeCommunityListModal();
  10482. showToast('Success', 'Community list saved', 'success');
  10483. loadDynamicRouting();
  10484. } else {
  10485. const err = await res.json();
  10486. showToast('Error', err.error || 'Failed to save community list', 'error');
  10487. }
  10488. } catch (err) {
  10489. showToast('Error', err.message, 'error');
  10490. }
  10491. }
  10492. async function deleteCommunityList(id) {
  10493. if (!confirm('Are you sure you want to delete this community list?')) return;
  10494. try {
  10495. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10496. if (res.ok) {
  10497. showToast('Deleted', 'Community list removed', 'info');
  10498. loadDynamicRouting();
  10499. } else {
  10500. const err = await res.json();
  10501. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10502. }
  10503. } catch (err) {
  10504. showToast('Error', err.message, 'error');
  10505. }
  10506. }
  10507. async function toggleCommunityListState(id, disabled) {
  10508. try {
  10509. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10510. method: 'POST',
  10511. headers: { 'Content-Type': 'application/json' },
  10512. body: JSON.stringify({ disabled })
  10513. });
  10514. if (res.ok) {
  10515. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10516. loadDynamicRouting();
  10517. } else {
  10518. const err = await res.json();
  10519. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10520. }
  10521. } catch (err) {
  10522. showToast('Error', err.message, 'error');
  10523. }
  10524. }
  10525. // -------------------------------------------------------------
  10526. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10527. // -------------------------------------------------------------
  10528. function openAddASListModal() {
  10529. document.getElementById('modal-rf-al-id').value = '';
  10530. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10531. document.getElementById('modal-rf-al-name').value = '';
  10532. document.getElementById('modal-rf-al-range').value = '';
  10533. document.getElementById('modal-rf-al-comment').value = '';
  10534. document.getElementById('modal-rf-al-disabled').checked = false;
  10535. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10536. }
  10537. function openEditASListModal(id) {
  10538. const al = (state.routingASLists || []).find(item => item.id === id);
  10539. if (!al) return;
  10540. document.getElementById('modal-rf-al-id').value = al.id;
  10541. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10542. document.getElementById('modal-rf-al-name').value = al.name || '';
  10543. document.getElementById('modal-rf-al-range').value = al.range || '';
  10544. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10545. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10546. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10547. }
  10548. function closeASListModal() {
  10549. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10550. }
  10551. async function submitASList(e) {
  10552. e.preventDefault();
  10553. const payload = {
  10554. id: document.getElementById('modal-rf-al-id').value,
  10555. name: document.getElementById('modal-rf-al-name').value.trim(),
  10556. range: document.getElementById('modal-rf-al-range').value.trim(),
  10557. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10558. disabled: document.getElementById('modal-rf-al-disabled').checked
  10559. };
  10560. try {
  10561. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10562. method: 'POST',
  10563. headers: { 'Content-Type': 'application/json' },
  10564. body: JSON.stringify(payload)
  10565. });
  10566. if (res.ok) {
  10567. closeASListModal();
  10568. showToast('Success', 'AS number list saved', 'success');
  10569. loadDynamicRouting();
  10570. } else {
  10571. const err = await res.json();
  10572. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10573. }
  10574. } catch (err) {
  10575. showToast('Error', err.message, 'error');
  10576. }
  10577. }
  10578. async function deleteASList(id) {
  10579. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10580. try {
  10581. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10582. if (res.ok) {
  10583. showToast('Deleted', 'AS list removed', 'info');
  10584. loadDynamicRouting();
  10585. } else {
  10586. const err = await res.json();
  10587. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10588. }
  10589. } catch (err) {
  10590. showToast('Error', err.message, 'error');
  10591. }
  10592. }
  10593. async function toggleASListState(id, disabled) {
  10594. try {
  10595. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10596. method: 'POST',
  10597. headers: { 'Content-Type': 'application/json' },
  10598. body: JSON.stringify({ disabled })
  10599. });
  10600. if (res.ok) {
  10601. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10602. loadDynamicRouting();
  10603. } else {
  10604. const err = await res.json();
  10605. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10606. }
  10607. } catch (err) {
  10608. showToast('Error', err.message, 'error');
  10609. }
  10610. }
  10611. // ==========================================
  10612. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10613. // ==========================================
  10614. function loadToolsView() {
  10615. populateToolsInterfaces();
  10616. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10617. }
  10618. function populateToolsInterfaces() {
  10619. const pingSel = document.getElementById('tools-ping-iface');
  10620. const traceSel = document.getElementById('tools-tr-iface');
  10621. let opts = '<option value="">Auto (Default Route)</option>';
  10622. if (Array.isArray(state.interfaces)) {
  10623. state.interfaces.forEach(iface => {
  10624. if (iface.name) {
  10625. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10626. }
  10627. });
  10628. }
  10629. if (pingSel) {
  10630. const cur = pingSel.value;
  10631. pingSel.innerHTML = opts;
  10632. if (cur) pingSel.value = cur;
  10633. }
  10634. if (traceSel) {
  10635. const cur = traceSel.value;
  10636. traceSel.innerHTML = opts;
  10637. if (cur) traceSel.value = cur;
  10638. }
  10639. }
  10640. function switchToolsSubTab(subTab) {
  10641. state.activeToolsSubTab = subTab;
  10642. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10643. tabs.forEach(t => {
  10644. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10645. const view = document.getElementById(`tools-view-${t}`);
  10646. if (btn) {
  10647. if (t === subTab) {
  10648. 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';
  10649. } else {
  10650. 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';
  10651. }
  10652. }
  10653. if (view) {
  10654. if (t === subTab) {
  10655. view.classList.remove('hidden');
  10656. } else {
  10657. view.classList.add('hidden');
  10658. }
  10659. }
  10660. });
  10661. }
  10662. function setPortPreset(port) {
  10663. const input = document.getElementById('tools-port-num');
  10664. if (input) input.value = port;
  10665. }
  10666. let pingAbortController = null;
  10667. let tracerouteAbortController = null;
  10668. function clearPingTable() {
  10669. const tbody = document.getElementById('tools-ping-tbody');
  10670. if (tbody) tbody.innerHTML = '';
  10671. const rawEl = document.getElementById('tools-ping-raw');
  10672. if (rawEl) rawEl.innerText = '';
  10673. const sentEl = document.getElementById('tools-ping-stat-sent');
  10674. if (sentEl) sentEl.innerText = '0';
  10675. const recvEl = document.getElementById('tools-ping-stat-recv');
  10676. if (recvEl) recvEl.innerText = '0';
  10677. const lossEl = document.getElementById('tools-ping-stat-loss');
  10678. if (lossEl) lossEl.innerText = '0%';
  10679. const avgEl = document.getElementById('tools-ping-stat-avg');
  10680. if (avgEl) avgEl.innerText = '0 ms';
  10681. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10682. if (minMaxEl) minMaxEl.innerText = '-';
  10683. const badge = document.getElementById('tools-ping-status-badge');
  10684. if (badge) {
  10685. badge.className = '';
  10686. badge.innerText = '';
  10687. }
  10688. }
  10689. function clearTracerouteTable() {
  10690. const tbody = document.getElementById('tools-tr-tbody');
  10691. if (tbody) tbody.innerHTML = '';
  10692. const rawEl = document.getElementById('tools-tr-raw');
  10693. if (rawEl) rawEl.innerText = '';
  10694. const statHops = document.getElementById('tools-tr-hops-count');
  10695. if (statHops) statHops.innerText = '0 Hops';
  10696. }
  10697. function resetPingButton() {
  10698. const btn = document.getElementById('tools-ping-btn');
  10699. const btnText = document.getElementById('tools-ping-btn-text');
  10700. const spinner = document.getElementById('tools-ping-spinner');
  10701. if (btn) {
  10702. btn.disabled = false;
  10703. 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';
  10704. }
  10705. if (btnText) btnText.innerText = 'Start Ping';
  10706. if (spinner) spinner.classList.add('hidden');
  10707. }
  10708. function setPingRunningButton() {
  10709. const btn = document.getElementById('tools-ping-btn');
  10710. const btnText = document.getElementById('tools-ping-btn-text');
  10711. const spinner = document.getElementById('tools-ping-spinner');
  10712. if (btn) {
  10713. btn.disabled = false;
  10714. 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';
  10715. }
  10716. if (btnText) btnText.innerText = 'Stop Ping';
  10717. if (spinner) spinner.classList.remove('hidden');
  10718. }
  10719. function resetTracerouteButton() {
  10720. const btn = document.getElementById('tools-tr-btn');
  10721. const btnText = document.getElementById('tools-tr-btn-text');
  10722. const spinner = document.getElementById('tools-tr-spinner');
  10723. if (btn) {
  10724. btn.disabled = false;
  10725. 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';
  10726. }
  10727. if (btnText) btnText.innerText = 'Start Traceroute';
  10728. if (spinner) spinner.classList.add('hidden');
  10729. }
  10730. function setTracerouteRunningButton() {
  10731. const btn = document.getElementById('tools-tr-btn');
  10732. const btnText = document.getElementById('tools-tr-btn-text');
  10733. const spinner = document.getElementById('tools-tr-spinner');
  10734. if (btn) {
  10735. btn.disabled = false;
  10736. 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';
  10737. }
  10738. if (btnText) btnText.innerText = 'Stop Traceroute';
  10739. if (spinner) spinner.classList.remove('hidden');
  10740. }
  10741. async function executePing(e) {
  10742. if (e) e.preventDefault();
  10743. // If already running, clicking the button stops the stream!
  10744. if (pingAbortController) {
  10745. pingAbortController.abort();
  10746. pingAbortController = null;
  10747. resetPingButton();
  10748. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10749. return;
  10750. }
  10751. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10752. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10753. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10754. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10755. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10756. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10757. if (!target) {
  10758. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10759. return;
  10760. }
  10761. clearPingTable();
  10762. const resCard = document.getElementById('tools-ping-results');
  10763. if (resCard) resCard.classList.remove('hidden');
  10764. pingAbortController = new AbortController();
  10765. setPingRunningButton();
  10766. try {
  10767. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10768. method: 'POST',
  10769. headers: { 'Content-Type': 'application/json' },
  10770. body: JSON.stringify({
  10771. target,
  10772. count,
  10773. size,
  10774. timeout,
  10775. interface: iface,
  10776. dont_frag: dontFrag
  10777. }),
  10778. signal: pingAbortController.signal
  10779. });
  10780. if (!res.ok) {
  10781. const errText = await res.text();
  10782. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10783. resetPingButton();
  10784. pingAbortController = null;
  10785. return;
  10786. }
  10787. const reader = res.body.getReader();
  10788. const decoder = new TextDecoder('utf-8');
  10789. let buffer = '';
  10790. while (true) {
  10791. const { done, value } = await reader.read();
  10792. if (done) break;
  10793. buffer += decoder.decode(value, { stream: true });
  10794. const blocks = buffer.split('\n\n');
  10795. buffer = blocks.pop() || '';
  10796. for (const block of blocks) {
  10797. const trimmed = block.trim();
  10798. if (!trimmed) continue;
  10799. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10800. try {
  10801. const evt = JSON.parse(line);
  10802. handleLivePingEvent(evt);
  10803. } catch (parseErr) {
  10804. console.warn('Ping SSE parse error:', parseErr, line);
  10805. }
  10806. }
  10807. }
  10808. } catch (err) {
  10809. if (err.name === 'AbortError') {
  10810. // User aborted normally
  10811. } else {
  10812. showToast('Ping Error', err.message, 'error');
  10813. }
  10814. } finally {
  10815. pingAbortController = null;
  10816. resetPingButton();
  10817. }
  10818. }
  10819. function handleLivePingEvent(evt) {
  10820. const sentEl = document.getElementById('tools-ping-stat-sent');
  10821. const recvEl = document.getElementById('tools-ping-stat-recv');
  10822. const lossEl = document.getElementById('tools-ping-stat-loss');
  10823. const avgEl = document.getElementById('tools-ping-stat-avg');
  10824. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10825. const badge = document.getElementById('tools-ping-status-badge');
  10826. const tbody = document.getElementById('tools-ping-tbody');
  10827. const rawEl = document.getElementById('tools-ping-raw');
  10828. if (evt.raw && rawEl) {
  10829. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10830. rawEl.scrollTop = rawEl.scrollHeight;
  10831. }
  10832. if (evt.type === 'reply') {
  10833. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10834. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10835. if (lossEl && evt.packet_loss_pct !== undefined) {
  10836. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10837. lossEl.className = evt.packet_loss_pct === 0
  10838. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10839. : (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');
  10840. }
  10841. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10842. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10843. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10844. }
  10845. if (badge) {
  10846. if (evt.packet_loss_pct === 0) {
  10847. 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';
  10848. badge.innerText = '100% OK';
  10849. } else {
  10850. 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';
  10851. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10852. }
  10853. }
  10854. if (tbody) {
  10855. const tr = document.createElement('tr');
  10856. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10857. tr.innerHTML = `
  10858. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10859. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10860. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10861. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10862. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10863. <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>
  10864. `;
  10865. tbody.appendChild(tr);
  10866. }
  10867. } else if (evt.type === 'timeout') {
  10868. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10869. if (lossEl && evt.packet_loss_pct !== undefined) {
  10870. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10871. 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';
  10872. }
  10873. if (badge) {
  10874. 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';
  10875. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10876. }
  10877. if (tbody) {
  10878. const tr = document.createElement('tr');
  10879. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10880. tr.innerHTML = `
  10881. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10882. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10883. <td class="py-2 px-3 text-slate-600">--</td>
  10884. <td class="py-2 px-3 text-slate-600">--</td>
  10885. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10886. <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>
  10887. `;
  10888. tbody.appendChild(tr);
  10889. }
  10890. } else if (evt.type === 'unreach') {
  10891. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10892. if (lossEl && evt.packet_loss_pct !== undefined) {
  10893. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10894. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10895. }
  10896. if (badge) {
  10897. 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';
  10898. badge.innerText = 'UNREACHABLE';
  10899. }
  10900. if (tbody) {
  10901. const tr = document.createElement('tr');
  10902. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10903. tr.innerHTML = `
  10904. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10905. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10906. <td class="py-2 px-3 text-slate-600">--</td>
  10907. <td class="py-2 px-3 text-slate-600">--</td>
  10908. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10909. <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>
  10910. `;
  10911. tbody.appendChild(tr);
  10912. }
  10913. } else if (evt.type === 'stats') {
  10914. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10915. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10916. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10917. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10918. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10919. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10920. }
  10921. } else if (evt.type === 'done') {
  10922. 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');
  10923. }
  10924. }
  10925. async function executeTraceroute(e) {
  10926. if (e) e.preventDefault();
  10927. if (tracerouteAbortController) {
  10928. tracerouteAbortController.abort();
  10929. tracerouteAbortController = null;
  10930. resetTracerouteButton();
  10931. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10932. return;
  10933. }
  10934. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10935. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10936. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10937. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10938. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10939. if (!target) {
  10940. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10941. return;
  10942. }
  10943. clearTracerouteTable();
  10944. const resCard = document.getElementById('tools-tr-results');
  10945. if (resCard) resCard.classList.remove('hidden');
  10946. tracerouteAbortController = new AbortController();
  10947. setTracerouteRunningButton();
  10948. try {
  10949. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10950. method: 'POST',
  10951. headers: { 'Content-Type': 'application/json' },
  10952. body: JSON.stringify({
  10953. target,
  10954. max_hops: maxHops,
  10955. protocol,
  10956. interface: iface,
  10957. resolve
  10958. }),
  10959. signal: tracerouteAbortController.signal
  10960. });
  10961. if (!res.ok) {
  10962. const errText = await res.text();
  10963. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10964. resetTracerouteButton();
  10965. tracerouteAbortController = null;
  10966. return;
  10967. }
  10968. const reader = res.body.getReader();
  10969. const decoder = new TextDecoder('utf-8');
  10970. let buffer = '';
  10971. while (true) {
  10972. const { done, value } = await reader.read();
  10973. if (done) break;
  10974. buffer += decoder.decode(value, { stream: true });
  10975. const blocks = buffer.split('\n\n');
  10976. buffer = blocks.pop() || '';
  10977. for (const block of blocks) {
  10978. const trimmed = block.trim();
  10979. if (!trimmed) continue;
  10980. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10981. try {
  10982. const evt = JSON.parse(line);
  10983. handleLiveTracerouteEvent(evt);
  10984. } catch (parseErr) {
  10985. console.warn('Traceroute SSE parse error:', parseErr, line);
  10986. }
  10987. }
  10988. }
  10989. } catch (err) {
  10990. if (err.name === 'AbortError') {
  10991. // User aborted normally
  10992. } else {
  10993. showToast('Traceroute Error', err.message, 'error');
  10994. }
  10995. } finally {
  10996. tracerouteAbortController = null;
  10997. resetTracerouteButton();
  10998. }
  10999. }
  11000. function handleLiveTracerouteEvent(evt) {
  11001. const statHops = document.getElementById('tools-tr-hops-count');
  11002. const tbody = document.getElementById('tools-tr-tbody');
  11003. const rawEl = document.getElementById('tools-tr-raw');
  11004. if (evt.raw && rawEl) {
  11005. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11006. rawEl.scrollTop = rawEl.scrollHeight;
  11007. }
  11008. if (evt.hops_count !== undefined && statHops) {
  11009. statHops.innerText = `${evt.hops_count} Hops`;
  11010. }
  11011. if (evt.type === 'hop' && evt.hop && tbody) {
  11012. const h = evt.hop;
  11013. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11014. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11015. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11016. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11017. const tr = document.createElement('tr');
  11018. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11019. tr.innerHTML = `
  11020. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11021. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11022. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11023. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11024. <td class="py-2.5 px-3 text-right">
  11025. ${isTimeout
  11026. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11027. : '<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>'}
  11028. </td>
  11029. `;
  11030. tbody.appendChild(tr);
  11031. } else if (evt.type === 'done') {
  11032. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11033. }
  11034. }
  11035. async function executeMTR(e) {
  11036. if (e) e.preventDefault();
  11037. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11038. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11039. if (!target) {
  11040. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11041. return;
  11042. }
  11043. const btn = document.getElementById('tools-mtr-btn');
  11044. const spinner = document.getElementById('tools-mtr-spinner');
  11045. if (btn) btn.disabled = true;
  11046. if (spinner) spinner.classList.remove('hidden');
  11047. try {
  11048. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11049. method: 'POST',
  11050. headers: { 'Content-Type': 'application/json' },
  11051. body: JSON.stringify({ target, count: cycles })
  11052. });
  11053. const data = await res.json();
  11054. if (!res.ok) {
  11055. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11056. return;
  11057. }
  11058. const resCard = document.getElementById('tools-mtr-results');
  11059. if (resCard) resCard.classList.remove('hidden');
  11060. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11061. const statHops = document.getElementById('tools-mtr-hops-count');
  11062. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11063. const tbody = document.getElementById('tools-mtr-tbody');
  11064. if (tbody) {
  11065. if (hopsCount > 0) {
  11066. tbody.innerHTML = data.hops.map(h => {
  11067. 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');
  11068. return `
  11069. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11070. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11071. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11072. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11073. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11074. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11075. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11076. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11077. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11078. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11079. </tr>
  11080. `;
  11081. }).join('');
  11082. } else {
  11083. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11084. }
  11085. }
  11086. const rawEl = document.getElementById('tools-mtr-raw');
  11087. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11088. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11089. } catch (err) {
  11090. showToast('MTR Error', err.message, 'error');
  11091. } finally {
  11092. if (btn) btn.disabled = false;
  11093. if (spinner) spinner.classList.add('hidden');
  11094. }
  11095. }
  11096. async function executeDNS(e) {
  11097. if (e) e.preventDefault();
  11098. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11099. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11100. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11101. if (!domain) {
  11102. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11103. return;
  11104. }
  11105. const btn = document.getElementById('tools-dns-btn');
  11106. const spinner = document.getElementById('tools-dns-spinner');
  11107. if (btn) btn.disabled = true;
  11108. if (spinner) spinner.classList.remove('hidden');
  11109. try {
  11110. const res = await fetch(`${API_BASE}/tools/dns`, {
  11111. method: 'POST',
  11112. headers: { 'Content-Type': 'application/json' },
  11113. body: JSON.stringify({ domain, type, server })
  11114. });
  11115. const data = await res.json();
  11116. if (!res.ok) {
  11117. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11118. return;
  11119. }
  11120. const resCard = document.getElementById('tools-dns-results');
  11121. if (resCard) resCard.classList.remove('hidden');
  11122. const metaEl = document.getElementById('tools-dns-meta');
  11123. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11124. const tbody = document.getElementById('tools-dns-tbody');
  11125. if (tbody) {
  11126. if (Array.isArray(data.records) && data.records.length > 0) {
  11127. tbody.innerHTML = data.records.map(r => `
  11128. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11129. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11130. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11131. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11132. <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>
  11133. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11134. </tr>
  11135. `).join('');
  11136. } else {
  11137. 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>`;
  11138. }
  11139. }
  11140. const rawEl = document.getElementById('tools-dns-raw');
  11141. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11142. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11143. } catch (err) {
  11144. showToast('DNS Error', err.message, 'error');
  11145. } finally {
  11146. if (btn) btn.disabled = false;
  11147. if (spinner) spinner.classList.add('hidden');
  11148. }
  11149. }
  11150. async function executePortProbe(e) {
  11151. if (e) e.preventDefault();
  11152. const target = document.getElementById('tools-port-target')?.value?.trim();
  11153. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11154. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11155. if (!target || !port) {
  11156. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11157. return;
  11158. }
  11159. const btn = document.getElementById('tools-port-btn');
  11160. const spinner = document.getElementById('tools-port-spinner');
  11161. if (btn) btn.disabled = true;
  11162. if (spinner) spinner.classList.remove('hidden');
  11163. try {
  11164. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11165. method: 'POST',
  11166. headers: { 'Content-Type': 'application/json' },
  11167. body: JSON.stringify({ target, port, timeout })
  11168. });
  11169. const data = await res.json();
  11170. if (!res.ok) {
  11171. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11172. return;
  11173. }
  11174. const resCard = document.getElementById('tools-port-results');
  11175. if (resCard) resCard.classList.remove('hidden');
  11176. const banner = document.getElementById('tools-port-banner');
  11177. const icon = document.getElementById('tools-port-icon');
  11178. const title = document.getElementById('tools-port-title');
  11179. const sub = document.getElementById('tools-port-sub');
  11180. const latency = document.getElementById('tools-port-latency');
  11181. if (data.open) {
  11182. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11183. if (icon) {
  11184. 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';
  11185. icon.innerText = '✓';
  11186. }
  11187. if (title) {
  11188. title.className = 'text-sm font-bold text-emerald-300';
  11189. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11190. }
  11191. if (sub) {
  11192. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11193. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11194. }
  11195. if (latency) {
  11196. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11197. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11198. }
  11199. } else {
  11200. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11201. if (icon) {
  11202. 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';
  11203. icon.innerText = '✕';
  11204. }
  11205. if (title) {
  11206. title.className = 'text-sm font-bold text-rose-300';
  11207. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11208. }
  11209. if (sub) {
  11210. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11211. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11212. }
  11213. if (latency) {
  11214. latency.className = 'text-base font-bold font-mono text-slate-500';
  11215. latency.innerText = '--';
  11216. }
  11217. }
  11218. const rawEl = document.getElementById('tools-port-raw');
  11219. 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'}`);
  11220. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11221. } catch (err) {
  11222. showToast('Probe Error', err.message, 'error');
  11223. } finally {
  11224. if (btn) btn.disabled = false;
  11225. if (spinner) spinner.classList.add('hidden');
  11226. }
  11227. }
  11228. // ==========================================
  11229. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11230. // ==========================================
  11231. async function loadDHCPClients(showToastMsg = false) {
  11232. try {
  11233. const [clientsRes, sumRes] = await Promise.all([
  11234. fetch(`${API_BASE}/dhcp/clients`),
  11235. fetch(`${API_BASE}/dhcp/clients/summary`)
  11236. ]);
  11237. if (clientsRes.ok) {
  11238. state.dhcpClients = await clientsRes.json();
  11239. }
  11240. if (sumRes.ok) {
  11241. state.dhcpSummary = await sumRes.json();
  11242. }
  11243. renderDHCPClients();
  11244. updateDHCPSummaryCards();
  11245. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11246. if (bDhcp && state.dhcpSummary) {
  11247. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11248. }
  11249. if (showToastMsg) {
  11250. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11251. }
  11252. } catch (err) {
  11253. console.error('Failed to load DHCP clients:', err);
  11254. if (showToastMsg) {
  11255. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11256. }
  11257. }
  11258. }
  11259. function updateDHCPSummaryCards() {
  11260. const sum = state.dhcpSummary || {
  11261. total_clients: (state.dhcpClients || []).length,
  11262. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11263. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11264. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11265. };
  11266. const totalEl = document.getElementById('dhcp-stat-total');
  11267. const boundEl = document.getElementById('dhcp-stat-bound');
  11268. const searchEl = document.getElementById('dhcp-stat-searching');
  11269. const disEl = document.getElementById('dhcp-stat-disabled');
  11270. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11271. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11272. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11273. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11274. }
  11275. function renderDHCPClients() {
  11276. const tbody = document.getElementById('dhcp-clients-tbody');
  11277. const emptyState = document.getElementById('dhcp-clients-empty');
  11278. if (!tbody) return;
  11279. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11280. if (clients.length === 0) {
  11281. tbody.innerHTML = '';
  11282. if (emptyState) emptyState.classList.remove('hidden');
  11283. return;
  11284. }
  11285. if (emptyState) emptyState.classList.add('hidden');
  11286. tbody.innerHTML = clients.map(c => {
  11287. let statusBadge = '';
  11288. if (!c.enabled) {
  11289. 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>';
  11290. } else if (c.status === 'bound') {
  11291. 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>';
  11292. } else if (c.status === 'searching') {
  11293. 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>';
  11294. } else if (c.status === 'stopped') {
  11295. 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>';
  11296. } else {
  11297. 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>`;
  11298. }
  11299. 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>';
  11300. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11301. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11302. 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>';
  11303. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11304. // Option flags
  11305. const flags = [];
  11306. 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>');
  11307. 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>');
  11308. 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>');
  11309. 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>`);
  11310. return `
  11311. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11312. <td class="py-3 px-4">
  11313. <div class="flex items-center gap-2">
  11314. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11315. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11316. </div>
  11317. </td>
  11318. <td class="py-3 px-4">${statusBadge}</td>
  11319. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11320. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11321. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11322. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11323. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11324. <td class="py-3 px-4">
  11325. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11326. </td>
  11327. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11328. ${c.enabled ? `
  11329. <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>
  11330. <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>
  11331. <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>
  11332. ` : `
  11333. <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>
  11334. `}
  11335. <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>
  11336. <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>
  11337. </td>
  11338. </tr>
  11339. `;
  11340. }).join('');
  11341. }
  11342. function openDHCPClientModal(clientId = null) {
  11343. const modal = document.getElementById('modal-dhcp-client');
  11344. if (!modal) return;
  11345. const title = document.getElementById('modal-dhcp-title');
  11346. const idInput = document.getElementById('modal-dhcp-id');
  11347. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11348. const distInput = document.getElementById('modal-dhcp-distance');
  11349. const commentInput = document.getElementById('modal-dhcp-comment');
  11350. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11351. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11352. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11353. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11354. // Populate interfaces
  11355. if (ifaceSelect) {
  11356. let opts = '<option value="">Select interface...</option>';
  11357. const allIfaces = state.interfaces || [];
  11358. const allVlans = state.vlans || [];
  11359. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11360. // Group 1: Physical & Bridge Interfaces
  11361. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11362. allIfaces.forEach(i => {
  11363. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11364. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11365. });
  11366. opts += '</optgroup>';
  11367. // Group 2: VLAN Interfaces
  11368. if (allVlans.length > 0) {
  11369. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11370. allVlans.forEach(v => {
  11371. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11372. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11373. });
  11374. opts += '</optgroup>';
  11375. }
  11376. ifaceSelect.innerHTML = opts;
  11377. }
  11378. if (clientId) {
  11379. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11380. if (client) {
  11381. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11382. if (idInput) idInput.value = client.id;
  11383. if (ifaceSelect) {
  11384. ifaceSelect.value = client.interface;
  11385. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11386. }
  11387. if (distInput) distInput.value = client.default_route_distance || 1;
  11388. if (commentInput) commentInput.value = client.comment || '';
  11389. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11390. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11391. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11392. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11393. }
  11394. } else {
  11395. if (title) title.innerText = 'Add DHCP Client';
  11396. if (idInput) idInput.value = '';
  11397. if (ifaceSelect) {
  11398. ifaceSelect.value = '';
  11399. ifaceSelect.disabled = false;
  11400. }
  11401. if (distInput) distInput.value = 1;
  11402. if (commentInput) commentInput.value = '';
  11403. if (defRouteCheck) defRouteCheck.checked = true;
  11404. if (peerDnsCheck) peerDnsCheck.checked = true;
  11405. if (peerNtpCheck) peerNtpCheck.checked = true;
  11406. if (enabledCheck) enabledCheck.checked = true;
  11407. }
  11408. modal.classList.remove('hidden');
  11409. }
  11410. function openDHCPClientModalForIface(ifaceName) {
  11411. openDHCPClientModal();
  11412. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11413. if (ifaceSelect && ifaceName) {
  11414. ifaceSelect.value = ifaceName;
  11415. }
  11416. }
  11417. function closeDHCPClientModal() {
  11418. const modal = document.getElementById('modal-dhcp-client');
  11419. if (modal) modal.classList.add('hidden');
  11420. }
  11421. async function submitSaveDHCPClient(e) {
  11422. if (e) e.preventDefault();
  11423. const id = document.getElementById('modal-dhcp-id')?.value;
  11424. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11425. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11426. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11427. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11428. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11429. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11430. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11431. if (!id && !iface) {
  11432. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11433. return;
  11434. }
  11435. try {
  11436. let res;
  11437. if (id) {
  11438. // PUT update
  11439. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11440. method: 'PUT',
  11441. headers: { 'Content-Type': 'application/json' },
  11442. body: JSON.stringify({
  11443. enabled,
  11444. add_default_route: defRoute,
  11445. default_route_distance: distance,
  11446. use_peer_dns: peerDns,
  11447. use_peer_ntp: peerNtp,
  11448. comment
  11449. })
  11450. });
  11451. } else {
  11452. // POST create
  11453. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11454. method: 'POST',
  11455. headers: { 'Content-Type': 'application/json' },
  11456. body: JSON.stringify({
  11457. interface: iface,
  11458. enabled,
  11459. add_default_route: defRoute,
  11460. default_route_distance: distance,
  11461. use_peer_dns: peerDns,
  11462. use_peer_ntp: peerNtp,
  11463. comment
  11464. })
  11465. });
  11466. }
  11467. const data = await res.json();
  11468. if (!res.ok) {
  11469. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11470. return;
  11471. }
  11472. closeDHCPClientModal();
  11473. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11474. await loadDHCPClients();
  11475. fetchData(); // refresh interfaces list with new lease/status
  11476. } catch (err) {
  11477. showToast('Error', err.message, 'error');
  11478. }
  11479. }
  11480. async function toggleDHCPClientState(id, enabled) {
  11481. try {
  11482. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11483. method: 'POST',
  11484. headers: { 'Content-Type': 'application/json' },
  11485. body: JSON.stringify({ enabled })
  11486. });
  11487. const data = await res.json();
  11488. if (!res.ok) {
  11489. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11490. return;
  11491. }
  11492. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11493. await loadDHCPClients();
  11494. fetchData();
  11495. } catch (err) {
  11496. showToast('Error', err.message, 'error');
  11497. }
  11498. }
  11499. async function renewDHCPClient(id) {
  11500. try {
  11501. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11502. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11503. method: 'POST'
  11504. });
  11505. const data = await res.json();
  11506. if (!res.ok) {
  11507. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11508. return;
  11509. }
  11510. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11511. setTimeout(() => {
  11512. loadDHCPClients();
  11513. fetchData();
  11514. }, 1500);
  11515. } catch (err) {
  11516. showToast('Error', err.message, 'error');
  11517. }
  11518. }
  11519. async function releaseDHCPClient(id) {
  11520. try {
  11521. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11522. method: 'POST'
  11523. });
  11524. const data = await res.json();
  11525. if (!res.ok) {
  11526. showToast('Error', data.error || 'Failed to release lease', 'error');
  11527. return;
  11528. }
  11529. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11530. await loadDHCPClients();
  11531. fetchData();
  11532. } catch (err) {
  11533. showToast('Error', err.message, 'error');
  11534. }
  11535. }
  11536. async function deleteDHCPClient(id, ifaceName) {
  11537. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11538. return;
  11539. }
  11540. try {
  11541. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11542. method: 'DELETE'
  11543. });
  11544. const data = await res.json();
  11545. if (!res.ok) {
  11546. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11547. return;
  11548. }
  11549. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11550. await loadDHCPClients();
  11551. fetchData();
  11552. } catch (err) {
  11553. showToast('Error', err.message, 'error');
  11554. }
  11555. }
  11556. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11557. async function loadDHCPServer(populate = true) {
  11558. try {
  11559. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11560. fetch(`${API_BASE}/dhcp-server/summary`),
  11561. fetch(`${API_BASE}/dhcp-server/servers`),
  11562. fetch(`${API_BASE}/dhcp-server/networks`),
  11563. fetch(`${API_BASE}/dhcp-server/leases`),
  11564. fetch(`${API_BASE}/dhcp-server/options`)
  11565. ]);
  11566. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11567. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11568. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11569. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11570. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11571. const sum = state.dhcpServerSummary || {};
  11572. const srvs = state.dhcpServers || [];
  11573. const nets = state.dhcpNetworks || [];
  11574. const leases = state.dhcpLeases || [];
  11575. const opts = state.dhcpOptions || [];
  11576. // KPI Cards
  11577. const statActive = document.getElementById('dhcp-server-stat-active');
  11578. if (statActive) {
  11579. const activeCount = srvs.filter(s => s.running).length;
  11580. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11581. }
  11582. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11583. if (statLeases) {
  11584. statLeases.innerText = leases.length;
  11585. }
  11586. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11587. if (statLeasesSub) {
  11588. const dyn = leases.filter(l => l.dynamic).length;
  11589. const st = leases.filter(l => !l.dynamic).length;
  11590. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11591. }
  11592. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11593. if (statNetworks) {
  11594. statNetworks.innerText = nets.length;
  11595. }
  11596. // Subtab Badges
  11597. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11598. if (bSrv) bSrv.innerText = srvs.length;
  11599. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11600. if (bNet) bNet.innerText = nets.length;
  11601. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11602. if (bLease) bLease.innerText = leases.length;
  11603. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11604. if (bOpt) bOpt.innerText = opts.length;
  11605. // Sidebar Badge
  11606. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11607. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11608. renderCurrentDHCPServerTab();
  11609. } catch (err) {
  11610. console.error('Failed to load DHCP Server:', err);
  11611. }
  11612. }
  11613. function switchDHCPServerTab(tab) {
  11614. state.dhcpServerTab = tab;
  11615. const tabs = ['servers', 'networks', 'leases', 'options'];
  11616. tabs.forEach(t => {
  11617. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11618. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11619. if (panel) {
  11620. if (t === tab) panel.classList.remove('hidden');
  11621. else panel.classList.add('hidden');
  11622. }
  11623. if (btn) {
  11624. if (t === tab) {
  11625. 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';
  11626. } else {
  11627. 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';
  11628. }
  11629. }
  11630. });
  11631. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11632. if (addBtn) {
  11633. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11634. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11635. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11636. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11637. }
  11638. renderCurrentDHCPServerTab();
  11639. }
  11640. function handleDHCPServerPrimaryAdd() {
  11641. const tab = state.dhcpServerTab || 'servers';
  11642. if (tab === 'servers') openAddDHCPServerModal();
  11643. else if (tab === 'networks') openAddDHCPNetworkModal();
  11644. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11645. else if (tab === 'options') openAddDHCPOptionModal();
  11646. }
  11647. function renderCurrentDHCPServerTab() {
  11648. const tab = state.dhcpServerTab || 'servers';
  11649. if (tab === 'servers') renderDHCPServers();
  11650. else if (tab === 'networks') renderDHCPNetworks();
  11651. else if (tab === 'leases') renderDHCPLeases();
  11652. else if (tab === 'options') renderDHCPOptions();
  11653. }
  11654. function renderDHCPServers() {
  11655. const tbody = document.getElementById('dhcp-server-tbody');
  11656. const empty = document.getElementById('dhcp-server-empty');
  11657. if (!tbody) return;
  11658. tbody.innerHTML = '';
  11659. const servers = state.dhcpServers || [];
  11660. if (servers.length === 0) {
  11661. empty?.classList.remove('hidden');
  11662. return;
  11663. }
  11664. empty?.classList.add('hidden');
  11665. servers.forEach(s => {
  11666. const tr = document.createElement('tr');
  11667. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11668. tr.innerHTML = `
  11669. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11670. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11671. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11672. <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>
  11673. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11674. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11675. <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>
  11676. <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>
  11677. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11678. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11679. <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>
  11680. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11681. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11682. </td>
  11683. `;
  11684. tbody.appendChild(tr);
  11685. });
  11686. }
  11687. function renderDHCPNetworks() {
  11688. const tbody = document.getElementById('dhcp-networks-tbody');
  11689. const empty = document.getElementById('dhcp-networks-empty');
  11690. if (!tbody) return;
  11691. tbody.innerHTML = '';
  11692. const networks = state.dhcpNetworks || [];
  11693. if (networks.length === 0) {
  11694. empty?.classList.remove('hidden');
  11695. return;
  11696. }
  11697. empty?.classList.add('hidden');
  11698. networks.forEach(n => {
  11699. const tr = document.createElement('tr');
  11700. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11701. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11702. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11703. tr.innerHTML = `
  11704. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11705. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11706. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11707. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11708. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11709. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11710. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11711. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11712. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11713. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11714. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11715. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11716. </td>
  11717. `;
  11718. tbody.appendChild(tr);
  11719. });
  11720. }
  11721. function renderDHCPLeases() {
  11722. const tbody = document.getElementById('dhcp-leases-tbody');
  11723. const empty = document.getElementById('dhcp-leases-empty');
  11724. if (!tbody) return;
  11725. tbody.innerHTML = '';
  11726. const leases = state.dhcpLeases || [];
  11727. if (leases.length === 0) {
  11728. empty?.classList.remove('hidden');
  11729. return;
  11730. }
  11731. empty?.classList.add('hidden');
  11732. leases.forEach(l => {
  11733. const tr = document.createElement('tr');
  11734. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11735. 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>';
  11736. const statusBadge = l.status === 'bound'
  11737. ? '<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>'
  11738. : l.status === 'static'
  11739. ? '<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>'
  11740. : '<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>';
  11741. const makeStaticBtn = l.dynamic
  11742. ? `<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>`
  11743. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11744. tr.innerHTML = `
  11745. <td class="py-2.5 px-3 text-center">${flag}</td>
  11746. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11747. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11748. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11749. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11750. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11751. <td class="py-2.5 px-3">${statusBadge}</td>
  11752. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11753. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11754. ${makeStaticBtn}
  11755. </td>
  11756. `;
  11757. tbody.appendChild(tr);
  11758. });
  11759. }
  11760. function renderDHCPOptions() {
  11761. const tbody = document.getElementById('dhcp-options-tbody');
  11762. const empty = document.getElementById('dhcp-options-empty');
  11763. if (!tbody) return;
  11764. tbody.innerHTML = '';
  11765. const options = state.dhcpOptions || [];
  11766. if (options.length === 0) {
  11767. empty?.classList.remove('hidden');
  11768. return;
  11769. }
  11770. empty?.classList.add('hidden');
  11771. options.forEach(o => {
  11772. const tr = document.createElement('tr');
  11773. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11774. tr.innerHTML = `
  11775. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11776. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11777. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11778. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11779. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11780. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11781. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11782. </td>
  11783. `;
  11784. tbody.appendChild(tr);
  11785. });
  11786. }
  11787. // ==================== MODALS & ACTIONS: SERVER ====================
  11788. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11789. const sel = document.getElementById(elemId);
  11790. if (!sel) return;
  11791. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11792. const networks = state.dhcpNetworks || [];
  11793. networks.forEach(n => {
  11794. const opt = document.createElement('option');
  11795. opt.value = n.address;
  11796. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11797. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11798. opt.selected = true;
  11799. }
  11800. sel.appendChild(opt);
  11801. });
  11802. }
  11803. function onDHCPServerNetworkChange() {
  11804. const netSel = document.getElementById('dhcp-server-modal-network');
  11805. if (!netSel) return;
  11806. const netVal = netSel.value;
  11807. if (!netVal) return;
  11808. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11809. if (!poolInput) return;
  11810. // Auto-calculate suggested address pool based on subnet CIDR
  11811. const parts = netVal.split('/');
  11812. const ip = parts[0];
  11813. const cidr = parseInt(parts[1] || '24', 10);
  11814. if (cidr === 24) {
  11815. const octets = ip.split('.');
  11816. if (octets.length === 4) {
  11817. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11818. poolInput.value = `${base}.10-${base}.254`;
  11819. }
  11820. }
  11821. }
  11822. function openAddDHCPServerModal() {
  11823. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11824. document.getElementById('dhcp-server-modal-id').value = '';
  11825. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11826. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11827. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11828. document.getElementById('dhcp-server-modal-comment').value = '';
  11829. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11830. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11831. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11832. const networks = state.dhcpNetworks || [];
  11833. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11834. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11835. if (defaultNet) {
  11836. onDHCPServerNetworkChange();
  11837. }
  11838. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11839. }
  11840. function openEditDHCPServerModal(id) {
  11841. const s = (state.dhcpServers || []).find(item => item.id === id);
  11842. if (!s) return;
  11843. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11844. document.getElementById('dhcp-server-modal-id').value = s.id;
  11845. document.getElementById('dhcp-server-modal-name').value = s.name;
  11846. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11847. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11848. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11849. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11850. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11851. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11852. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11853. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11854. }
  11855. function closeDHCPServerModal() {
  11856. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11857. }
  11858. async function submitSaveDHCPServer(e) {
  11859. e.preventDefault();
  11860. const id = document.getElementById('dhcp-server-modal-id').value;
  11861. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11862. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11863. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11864. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11865. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11866. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11867. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11868. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11869. try {
  11870. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11871. method: 'POST',
  11872. headers: { 'Content-Type': 'application/json' },
  11873. body: JSON.stringify({
  11874. id,
  11875. name,
  11876. interface: iface,
  11877. network,
  11878. address_pool: pool,
  11879. lease_time: leaseTime,
  11880. authoritative,
  11881. disabled,
  11882. comment
  11883. })
  11884. });
  11885. if (res.ok) {
  11886. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11887. closeDHCPServerModal();
  11888. loadDHCPServer(false);
  11889. fetchData(false);
  11890. } else {
  11891. const err = await res.text();
  11892. showToast('Error', err, 'error');
  11893. }
  11894. } catch (err) {
  11895. showToast('Error', err.message, 'error');
  11896. }
  11897. }
  11898. async function toggleDHCPServerState(id, disabled) {
  11899. try {
  11900. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11901. method: 'POST',
  11902. headers: { 'Content-Type': 'application/json' },
  11903. body: JSON.stringify({ disabled })
  11904. });
  11905. if (res.ok) {
  11906. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11907. loadDHCPServer(false);
  11908. fetchData(false);
  11909. }
  11910. } catch (err) {
  11911. showToast('Error', err.message, 'error');
  11912. }
  11913. }
  11914. async function deleteDHCPServer(id, name) {
  11915. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11916. try {
  11917. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11918. if (res.ok) {
  11919. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11920. loadDHCPServer(false);
  11921. fetchData(false);
  11922. }
  11923. } catch (err) {
  11924. showToast('Error', err.message, 'error');
  11925. }
  11926. }
  11927. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11928. function openAddDHCPNetworkModal() {
  11929. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11930. document.getElementById('dhcp-network-modal-id').value = '';
  11931. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11932. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11933. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11934. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11935. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11936. document.getElementById('dhcp-network-modal-tftp').value = '';
  11937. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11938. document.getElementById('dhcp-network-modal-wins').value = '';
  11939. document.getElementById('dhcp-network-modal-netmask').value = '';
  11940. document.getElementById('dhcp-network-modal-comment').value = '';
  11941. renderDHCPNetworkOptionsCheckboxes([]);
  11942. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11943. }
  11944. function openEditDHCPNetworkModal(id) {
  11945. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11946. if (!n) return;
  11947. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11948. document.getElementById('dhcp-network-modal-id').value = n.id;
  11949. document.getElementById('dhcp-network-modal-address').value = n.address;
  11950. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11951. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11952. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11953. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11954. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11955. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11956. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11957. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11958. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11959. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11960. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11961. }
  11962. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  11963. const container = document.getElementById('dhcp-network-modal-options-list');
  11964. if (!container) return;
  11965. container.innerHTML = '';
  11966. const opts = state.dhcpOptions || [];
  11967. if (opts.length === 0) {
  11968. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  11969. return;
  11970. }
  11971. opts.forEach(o => {
  11972. const isChecked = selectedIds.includes(o.id);
  11973. const label = document.createElement('label');
  11974. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  11975. label.innerHTML = `
  11976. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  11977. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  11978. `;
  11979. container.appendChild(label);
  11980. });
  11981. }
  11982. function closeDHCPNetworkModal() {
  11983. document.getElementById('dhcp-network-modal').classList.add('hidden');
  11984. }
  11985. async function submitSaveDHCPNetwork(e) {
  11986. e.preventDefault();
  11987. const id = document.getElementById('dhcp-network-modal-id').value;
  11988. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  11989. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  11990. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  11991. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  11992. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  11993. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  11994. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  11995. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  11996. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  11997. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  11998. const selectedOpts = [];
  11999. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12000. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12001. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12002. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12003. try {
  12004. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12005. method: 'POST',
  12006. headers: { 'Content-Type': 'application/json' },
  12007. body: JSON.stringify({
  12008. id,
  12009. address,
  12010. gateway,
  12011. netmask,
  12012. dns_servers: dnsServers,
  12013. domain,
  12014. ntp_servers: ntpServers,
  12015. next_server: tftp,
  12016. boot_file_name: bootfile,
  12017. wins_servers: winsServers,
  12018. dhcp_options: selectedOpts,
  12019. comment
  12020. })
  12021. });
  12022. if (res.ok) {
  12023. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12024. closeDHCPNetworkModal();
  12025. loadDHCPServer(false);
  12026. fetchData(false);
  12027. } else {
  12028. const err = await res.text();
  12029. showToast('Error', err, 'error');
  12030. }
  12031. } catch (err) {
  12032. showToast('Error', err.message, 'error');
  12033. }
  12034. }
  12035. async function deleteDHCPNetwork(id, addr) {
  12036. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12037. try {
  12038. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12039. if (res.ok) {
  12040. showToast('Deleted', `Network ${addr} removed`, 'success');
  12041. loadDHCPServer(false);
  12042. fetchData(false);
  12043. }
  12044. } catch (err) {
  12045. showToast('Error', err.message, 'error');
  12046. }
  12047. }
  12048. // ==================== MODALS & ACTIONS: LEASES ====================
  12049. function openAddDHCPStaticLeaseModal() {
  12050. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12051. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12052. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12053. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12054. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12055. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12056. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12057. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12058. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12059. }
  12060. function closeDHCPStaticLeaseModal() {
  12061. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12062. }
  12063. async function submitSaveDHCPStaticLease(e) {
  12064. e.preventDefault();
  12065. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12066. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12067. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12068. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12069. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12070. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12071. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12072. try {
  12073. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12074. method: 'POST',
  12075. headers: { 'Content-Type': 'application/json' },
  12076. body: JSON.stringify({
  12077. id,
  12078. mac_address: mac,
  12079. address: ip,
  12080. hostname,
  12081. server,
  12082. comment,
  12083. disabled
  12084. })
  12085. });
  12086. if (res.ok) {
  12087. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12088. closeDHCPStaticLeaseModal();
  12089. loadDHCPServer(false);
  12090. fetchData(false);
  12091. } else {
  12092. const err = await res.text();
  12093. showToast('Error', err, 'error');
  12094. }
  12095. } catch (err) {
  12096. showToast('Error', err.message, 'error');
  12097. }
  12098. }
  12099. async function deleteDHCPStaticLease(id) {
  12100. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12101. try {
  12102. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12103. if (res.ok) {
  12104. showToast('Deleted', 'Static lease removed', 'success');
  12105. loadDHCPServer(false);
  12106. fetchData(false);
  12107. }
  12108. } catch (err) {
  12109. showToast('Error', err.message, 'error');
  12110. }
  12111. }
  12112. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12113. try {
  12114. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12115. method: 'POST',
  12116. headers: { 'Content-Type': 'application/json' },
  12117. body: JSON.stringify({
  12118. mac_address: mac,
  12119. address: ip,
  12120. hostname,
  12121. comment: comment || 'Converted to static'
  12122. })
  12123. });
  12124. if (res.ok) {
  12125. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12126. loadDHCPServer(false);
  12127. fetchData(false);
  12128. } else {
  12129. const err = await res.text();
  12130. showToast('Error', err, 'error');
  12131. }
  12132. } catch (err) {
  12133. showToast('Error', err.message, 'error');
  12134. }
  12135. }
  12136. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12137. function openAddDHCPOptionModal() {
  12138. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12139. document.getElementById('dhcp-option-modal-id').value = '';
  12140. document.getElementById('dhcp-option-modal-name').value = '';
  12141. document.getElementById('dhcp-option-modal-code').value = '';
  12142. document.getElementById('dhcp-option-modal-value').value = '';
  12143. document.getElementById('dhcp-option-modal-comment').value = '';
  12144. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12145. }
  12146. function openEditDHCPOptionModal(id) {
  12147. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12148. if (!o) return;
  12149. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12150. document.getElementById('dhcp-option-modal-id').value = o.id;
  12151. document.getElementById('dhcp-option-modal-name').value = o.name;
  12152. document.getElementById('dhcp-option-modal-code').value = o.code;
  12153. document.getElementById('dhcp-option-modal-value').value = o.value;
  12154. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12155. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12156. }
  12157. function closeDHCPOptionModal() {
  12158. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12159. }
  12160. async function submitSaveDHCPOption(e) {
  12161. e.preventDefault();
  12162. const id = document.getElementById('dhcp-option-modal-id').value;
  12163. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12164. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12165. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12166. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12167. try {
  12168. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12169. method: 'POST',
  12170. headers: { 'Content-Type': 'application/json' },
  12171. body: JSON.stringify({ id, name, code, value, comment })
  12172. });
  12173. if (res.ok) {
  12174. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12175. closeDHCPOptionModal();
  12176. loadDHCPServer(false);
  12177. fetchData(false);
  12178. } else {
  12179. const err = await res.text();
  12180. showToast('Error', err, 'error');
  12181. }
  12182. } catch (err) {
  12183. showToast('Error', err.message, 'error');
  12184. }
  12185. }
  12186. async function deleteDHCPOption(id, name) {
  12187. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12188. try {
  12189. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12190. if (res.ok) {
  12191. showToast('Deleted', `Option ${name} removed`, 'success');
  12192. loadDHCPServer(false);
  12193. fetchData(false);
  12194. }
  12195. } catch (err) {
  12196. showToast('Error', err.message, 'error');
  12197. }
  12198. }
  12199. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12200. function openDHCPServerSetupModal() {
  12201. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12202. onDHCPWizardIfaceChange();
  12203. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12204. }
  12205. function closeDHCPServerSetupModal() {
  12206. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12207. }
  12208. function onDHCPWizardIfaceChange() {
  12209. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12210. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12211. let ip = '192.168.88.1';
  12212. let prefix = '24';
  12213. if (iface && iface.ip_address) {
  12214. const parts = iface.ip_address.split('/');
  12215. ip = parts[0];
  12216. if (parts.length > 1) prefix = parts[1];
  12217. }
  12218. // Calculate subnet base (e.g. 192.168.88.0/24)
  12219. const ipParts = ip.split('.');
  12220. if (ipParts.length === 4) {
  12221. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12222. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12223. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12224. document.getElementById('dhcp-wizard-gateway').value = ip;
  12225. document.getElementById('dhcp-wizard-pool').value = pool;
  12226. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12227. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12228. }
  12229. }
  12230. async function submitDHCPServerSetupWizard(e) {
  12231. e.preventDefault();
  12232. const iface = document.getElementById('dhcp-wizard-iface').value;
  12233. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12234. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12235. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12236. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12237. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12238. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12239. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12240. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12241. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12242. try {
  12243. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12244. method: 'POST',
  12245. headers: { 'Content-Type': 'application/json' },
  12246. body: JSON.stringify({
  12247. interface: iface,
  12248. address_space: space,
  12249. gateway: gw,
  12250. address_pool: pool,
  12251. dns_servers: dnsServers,
  12252. lease_time: leaseTime,
  12253. ntp_servers: ntpServers,
  12254. next_server: tftp
  12255. })
  12256. });
  12257. if (res.ok) {
  12258. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12259. closeDHCPServerSetupModal();
  12260. loadDHCPServer(false);
  12261. fetchData(false);
  12262. } else {
  12263. const err = await res.text();
  12264. showToast('Error', err, 'error');
  12265. }
  12266. } catch (err) {
  12267. showToast('Error', err.message, 'error');
  12268. }
  12269. }
  12270. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12271. const sel = document.getElementById(elemId);
  12272. if (!sel) return;
  12273. sel.innerHTML = '<option value="">Select interface...</option>';
  12274. const ifaces = state.interfaces || [];
  12275. ifaces.forEach(i => {
  12276. if (i.name === 'lo') return;
  12277. const opt = document.createElement('option');
  12278. opt.value = i.name;
  12279. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12280. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12281. if (i.name === selectedVal) opt.selected = true;
  12282. sel.appendChild(opt);
  12283. });
  12284. }
  12285. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12286. function initTableSorting() {
  12287. document.querySelectorAll('table').forEach(setupSortableTable);
  12288. }
  12289. function setupSortableTable(table) {
  12290. const thead = table.querySelector('thead');
  12291. const tbody = table.querySelector('tbody');
  12292. if (!thead || !tbody) return;
  12293. const headerRows = thead.querySelectorAll('tr');
  12294. if (headerRows.length === 0) return;
  12295. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12296. ths.forEach((th, colIdx) => {
  12297. if (th._sortBound) return;
  12298. th._sortBound = true;
  12299. const rawText = th.innerText.trim().toLowerCase();
  12300. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12301. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12302. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12303. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12304. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12305. return;
  12306. }
  12307. th.classList.add('table-sortable', 'group');
  12308. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12309. let icon = th.querySelector('.table-sort-icon');
  12310. if (!icon) {
  12311. icon = document.createElement('span');
  12312. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12313. icon.innerHTML = '⇅';
  12314. th.appendChild(icon);
  12315. }
  12316. th.addEventListener('click', (e) => {
  12317. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12318. handleHeaderClick(table, th, colIdx);
  12319. });
  12320. });
  12321. if (!tbody._sortObserved) {
  12322. tbody._sortObserved = true;
  12323. let sortDebounceTimer = null;
  12324. const observer = new MutationObserver((mutations) => {
  12325. if (tbody._isSorting) return;
  12326. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12327. if (!hasChildChanges) return;
  12328. clearTimeout(sortDebounceTimer);
  12329. sortDebounceTimer = setTimeout(() => {
  12330. if (tbody._isSorting) return;
  12331. if (table._activeSort && table._activeSort.dir !== 'none') {
  12332. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12333. } else {
  12334. tagOriginalRowOrder(tbody);
  12335. }
  12336. }, 10);
  12337. });
  12338. observer.observe(tbody, { childList: true });
  12339. }
  12340. tagOriginalRowOrder(tbody);
  12341. }
  12342. function tagOriginalRowOrder(tbody) {
  12343. let idx = 0;
  12344. Array.from(tbody.children).forEach(tr => {
  12345. if (!tr.querySelector('td[colspan]')) {
  12346. if (!tr.hasAttribute('data-orig-idx')) {
  12347. tr.setAttribute('data-orig-idx', idx++);
  12348. }
  12349. }
  12350. });
  12351. }
  12352. function handleHeaderClick(table, th, colIdx) {
  12353. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12354. let newDir = 'asc';
  12355. if (currentSort.colIdx === colIdx) {
  12356. if (currentSort.dir === 'asc') newDir = 'desc';
  12357. else if (currentSort.dir === 'desc') newDir = 'none';
  12358. else newDir = 'asc';
  12359. } else {
  12360. newDir = 'asc';
  12361. }
  12362. table._activeSort = { colIdx, dir: newDir };
  12363. updateHeaderIcons(table, colIdx, newDir);
  12364. applyTableSort(table, colIdx, newDir, true);
  12365. }
  12366. function updateHeaderIcons(table, activeColIdx, dir) {
  12367. const thead = table.querySelector('thead');
  12368. if (!thead) return;
  12369. const ths = thead.querySelectorAll('th');
  12370. ths.forEach((th, idx) => {
  12371. const icon = th.querySelector('.table-sort-icon');
  12372. if (!icon) return;
  12373. if (idx === activeColIdx && dir !== 'none') {
  12374. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12375. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12376. th.classList.add('table-sorted-active');
  12377. } else {
  12378. icon.innerHTML = '⇅';
  12379. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12380. th.classList.remove('table-sorted-active');
  12381. }
  12382. });
  12383. }
  12384. function applyTableSort(table, colIdx, dir, userInitiated) {
  12385. const tbody = table.querySelector('tbody');
  12386. if (!tbody || tbody.children.length <= 1) return;
  12387. tbody._isSorting = true;
  12388. tagOriginalRowOrder(tbody);
  12389. // Group parent rows and any attached drawer/sub-rows
  12390. const groups = [];
  12391. let currentGroup = null;
  12392. Array.from(tbody.children).forEach(tr => {
  12393. if (tr.querySelector('td[colspan]')) {
  12394. if (currentGroup) {
  12395. currentGroup.subRows.push(tr);
  12396. } else {
  12397. groups.push({ mainRow: tr, subRows: [] });
  12398. }
  12399. } else {
  12400. currentGroup = { mainRow: tr, subRows: [] };
  12401. groups.push(currentGroup);
  12402. }
  12403. });
  12404. if (dir === 'none') {
  12405. groups.sort((a, b) => {
  12406. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12407. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12408. return idxA - idxB;
  12409. });
  12410. } else {
  12411. groups.sort((a, b) => {
  12412. const cellA = a.mainRow.children[colIdx];
  12413. const cellB = b.mainRow.children[colIdx];
  12414. const res = compareTableCells(cellA, cellB);
  12415. return dir === 'asc' ? res : -res;
  12416. });
  12417. }
  12418. // Re-append rows in sorted order
  12419. groups.forEach(g => {
  12420. tbody.appendChild(g.mainRow);
  12421. g.subRows.forEach(sub => tbody.appendChild(sub));
  12422. });
  12423. tbody._isSorting = false;
  12424. }
  12425. function getCellRawText(cell) {
  12426. if (!cell) return '';
  12427. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12428. const input = cell.querySelector('input, select');
  12429. if (input) {
  12430. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12431. return input.value;
  12432. }
  12433. return cell.innerText.trim();
  12434. }
  12435. function parseTrafficToNumber(str) {
  12436. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12437. if (!m) return null;
  12438. const num = parseFloat(m[1].replace(/,/g, ''));
  12439. if (isNaN(num)) return null;
  12440. const unit = m[2].toUpperCase();
  12441. let mult = 1;
  12442. if (unit.startsWith('K')) mult = 1024;
  12443. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12444. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12445. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12446. return num * mult;
  12447. }
  12448. function parseIpToNumber(str) {
  12449. const clean = str.replace(/^[!~]/, '').trim();
  12450. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12451. if (!m) return null;
  12452. const o1 = parseInt(m[1], 10);
  12453. const o2 = parseInt(m[2], 10);
  12454. const o3 = parseInt(m[3], 10);
  12455. const o4 = parseInt(m[4], 10);
  12456. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12457. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12458. }
  12459. function parseCompoundPackets(str) {
  12460. const m = str.match(/^([\d,]+)p/);
  12461. if (!m) return null;
  12462. return parseInt(m[1].replace(/,/g, ''), 10);
  12463. }
  12464. function compareTableCells(cellA, cellB) {
  12465. const a = getCellRawText(cellA);
  12466. const b = getCellRawText(cellB);
  12467. if (a === '' && b !== '') return 1;
  12468. if (b === '' && a !== '') return -1;
  12469. if (a === b) return 0;
  12470. // 1. IP Addresses / CIDR
  12471. const ipA = parseIpToNumber(a);
  12472. const ipB = parseIpToNumber(b);
  12473. if (ipA !== null && ipB !== null) return ipA - ipB;
  12474. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12475. const pktA = parseCompoundPackets(a);
  12476. const pktB = parseCompoundPackets(b);
  12477. if (pktA !== null && pktB !== null) return pktA - pktB;
  12478. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12479. const trafA = parseTrafficToNumber(a);
  12480. const trafB = parseTrafficToNumber(b);
  12481. if (trafA !== null && trafB !== null) return trafA - trafB;
  12482. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12483. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12484. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12485. const numA = Number(cleanNumA);
  12486. const numB = Number(cleanNumB);
  12487. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12488. return numA - numB;
  12489. }
  12490. // 5. Natural case-insensitive string compare
  12491. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12492. }
  12493. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12494. async function loadVRRP(showToastNotification = false) {
  12495. try {
  12496. const [instRes, sumRes] = await Promise.all([
  12497. fetch(`${API_BASE}/vrrp/instances`),
  12498. fetch(`${API_BASE}/vrrp/summary`)
  12499. ]);
  12500. if (instRes.ok) {
  12501. state.vrrpInstances = await instRes.json();
  12502. renderVRRP();
  12503. }
  12504. if (sumRes.ok) {
  12505. state.vrrpSummary = await sumRes.json();
  12506. renderVRRPSummary();
  12507. }
  12508. if (showToastNotification) {
  12509. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12510. }
  12511. } catch (err) {
  12512. console.error('Failed to load VRRP:', err);
  12513. }
  12514. }
  12515. function renderVRRPSummary() {
  12516. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12517. const elTotal = document.getElementById('vrrp-stat-total');
  12518. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12519. const elMaster = document.getElementById('vrrp-stat-master');
  12520. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12521. const elBackup = document.getElementById('vrrp-stat-backup');
  12522. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12523. const bCount = document.getElementById('badge-vrrp-count');
  12524. if (bCount) bCount.innerText = s.total_instances || 0;
  12525. const dot = document.getElementById('badge-vrrp-dot');
  12526. if (dot) {
  12527. if (s.master_instances > 0) {
  12528. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12529. } else if (s.backup_instances > 0) {
  12530. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12531. } else {
  12532. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12533. }
  12534. }
  12535. }
  12536. function renderVRRP() {
  12537. const tbody = document.getElementById('vrrp-table-tbody');
  12538. const empty = document.getElementById('vrrp-table-empty');
  12539. if (!tbody) return;
  12540. tbody.innerHTML = '';
  12541. const instances = state.vrrpInstances || [];
  12542. if (instances.length === 0) {
  12543. empty?.classList.remove('hidden');
  12544. return;
  12545. }
  12546. empty?.classList.add('hidden');
  12547. instances.forEach(inst => {
  12548. const tr = document.createElement('tr');
  12549. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12550. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12551. 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>`;
  12552. if (inst.disabled) {
  12553. 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>`;
  12554. } else if (inst.state === 'MASTER') {
  12555. 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>`;
  12556. } else if (inst.state === 'BACKUP') {
  12557. 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>`;
  12558. } else if (inst.state === 'FAULT') {
  12559. 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>`;
  12560. }
  12561. // Render State Badge
  12562. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12563. if (!inst.disabled) {
  12564. if (inst.state === 'MASTER') {
  12565. 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>`;
  12566. } else if (inst.state === 'BACKUP') {
  12567. 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>`;
  12568. } else if (inst.state === 'FAULT') {
  12569. 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>`;
  12570. }
  12571. }
  12572. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12573. tr.innerHTML = `
  12574. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12575. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12576. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12577. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12578. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12579. <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>
  12580. <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>
  12581. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12582. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12583. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12584. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12585. <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>
  12586. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12587. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12588. </td>
  12589. `;
  12590. tbody.appendChild(tr);
  12591. });
  12592. }
  12593. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12594. const sel = document.getElementById(elemId);
  12595. if (!sel) return;
  12596. sel.innerHTML = '<option value="">Select interface...</option>';
  12597. const ifaces = state.interfaces || [];
  12598. ifaces.forEach(i => {
  12599. const opt = document.createElement('option');
  12600. opt.value = i.name;
  12601. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12602. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12603. sel.appendChild(opt);
  12604. });
  12605. }
  12606. function openAddVRRPModal() {
  12607. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12608. document.getElementById('modal-vrrp-id').value = '';
  12609. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12610. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12611. document.getElementById('modal-vrrp-priority').value = 100;
  12612. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12613. document.getElementById('modal-vrrp-version').value = '3';
  12614. document.getElementById('modal-vrrp-interval').value = 1;
  12615. document.getElementById('modal-vrrp-authtype').value = 'none';
  12616. document.getElementById('modal-vrrp-authpass').value = '';
  12617. document.getElementById('modal-vrrp-comment').value = '';
  12618. document.getElementById('modal-vrrp-preempt').checked = true;
  12619. document.getElementById('modal-vrrp-disabled').checked = false;
  12620. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12621. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12622. }
  12623. function openEditVRRPModal(id) {
  12624. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12625. if (!inst) return;
  12626. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12627. document.getElementById('modal-vrrp-id').value = inst.id;
  12628. document.getElementById('modal-vrrp-name').value = inst.name;
  12629. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12630. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12631. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12632. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12633. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12634. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12635. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12636. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12637. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12638. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12639. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12640. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12641. }
  12642. function closeVRRPModal() {
  12643. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12644. }
  12645. async function submitSaveVRRP(e) {
  12646. e.preventDefault();
  12647. const id = document.getElementById('modal-vrrp-id').value;
  12648. const name = document.getElementById('modal-vrrp-name').value.trim();
  12649. const iface = document.getElementById('modal-vrrp-iface').value;
  12650. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12651. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12652. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12653. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12654. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12655. const authType = document.getElementById('modal-vrrp-authtype').value;
  12656. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12657. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12658. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12659. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12660. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12661. try {
  12662. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12663. method: 'POST',
  12664. headers: { 'Content-Type': 'application/json' },
  12665. body: JSON.stringify({
  12666. id,
  12667. name,
  12668. interface: iface,
  12669. vrid,
  12670. priority,
  12671. virtual_ips: vips,
  12672. version,
  12673. interval,
  12674. auth_type: authType,
  12675. auth_password: authPass,
  12676. comment,
  12677. preempt,
  12678. disabled
  12679. })
  12680. });
  12681. if (res.ok) {
  12682. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12683. closeVRRPModal();
  12684. loadVRRP(false);
  12685. fetchData(false);
  12686. } else {
  12687. const err = await res.text();
  12688. showToast('Error', err, 'error');
  12689. }
  12690. } catch (err) {
  12691. showToast('Error', err.message, 'error');
  12692. }
  12693. }
  12694. async function deleteVRRP(id, name) {
  12695. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12696. try {
  12697. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12698. if (res.ok) {
  12699. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12700. loadVRRP(false);
  12701. fetchData(false);
  12702. } else {
  12703. const err = await res.text();
  12704. showToast('Error', err, 'error');
  12705. }
  12706. } catch (err) {
  12707. showToast('Error', err.message, 'error');
  12708. }
  12709. }
  12710. async function toggleVRRPState(id, disabled) {
  12711. try {
  12712. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12713. method: 'POST',
  12714. headers: { 'Content-Type': 'application/json' },
  12715. body: JSON.stringify({ disabled })
  12716. });
  12717. if (res.ok) {
  12718. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12719. loadVRRP(false);
  12720. fetchData(false);
  12721. } else {
  12722. const err = await res.text();
  12723. showToast('Error', err, 'error');
  12724. }
  12725. } catch (err) {
  12726. showToast('Error', err.message, 'error');
  12727. }
  12728. }
  12729. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12730. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12731. const docTableObserver = new MutationObserver((mutations) => {
  12732. let needsInit = false;
  12733. for (const m of mutations) {
  12734. for (const node of m.addedNodes) {
  12735. if (node.nodeType === 1) {
  12736. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12737. needsInit = true;
  12738. break;
  12739. }
  12740. }
  12741. }
  12742. if (needsInit) break;
  12743. }
  12744. if (needsInit) {
  12745. initTableSorting();
  12746. }
  12747. });
  12748. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12749. }
  12750. // =========================================================================
  12751. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  12752. // =========================================================================
  12753. const bwtestState = {
  12754. running: false,
  12755. pollTimer: null,
  12756. eventSource: null,
  12757. chartPoints: [],
  12758. maxChartPoints: 60,
  12759. serverConfig: null,
  12760. peakTx: 0,
  12761. peakRx: 0,
  12762. targetDuration: 10,
  12763. lastSampleIndex: 0
  12764. };
  12765. async function loadBwTestView() {
  12766. fetchBwTestServerStatus();
  12767. loadBwTestHistory();
  12768. resizeBwTestCanvas();
  12769. checkActiveBwTest();
  12770. }
  12771. async function fetchBwTestServerStatus() {
  12772. try {
  12773. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  12774. if (!res.ok) return;
  12775. const s = await res.json();
  12776. bwtestState.serverConfig = s;
  12777. // Update indicator and badges
  12778. const indicator = document.getElementById('bwtest-server-indicator');
  12779. const badge = document.getElementById('bwtest-server-badge');
  12780. const sideBadge = document.getElementById('badge-bwtest-server');
  12781. if (s.enabled && s.running) {
  12782. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12783. if (badge) {
  12784. badge.innerText = `Port ${s.port} (Active)`;
  12785. badge.className = 'text-emerald-400 font-bold';
  12786. }
  12787. if (sideBadge) {
  12788. sideBadge.innerText = s.port;
  12789. 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';
  12790. }
  12791. } else {
  12792. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  12793. if (badge) {
  12794. badge.innerText = `Disabled`;
  12795. badge.className = 'text-slate-500 font-bold';
  12796. }
  12797. if (sideBadge) {
  12798. sideBadge.innerText = 'Off';
  12799. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  12800. }
  12801. }
  12802. // Modal fields
  12803. const toggle = document.getElementById('bwtest-server-enable-toggle');
  12804. if (toggle) toggle.checked = !!s.enabled;
  12805. const portInp = document.getElementById('bwtest-server-port-input');
  12806. if (portInp) portInp.value = s.port || 2000;
  12807. const actSess = document.getElementById('bwtest-modal-active-sessions');
  12808. if (actSess) actSess.innerText = s.active_sessions || 0;
  12809. const totServ = document.getElementById('bwtest-modal-total-served');
  12810. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  12811. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  12812. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  12813. } catch (err) {
  12814. console.error('Failed to fetch BwTest server status:', err);
  12815. }
  12816. }
  12817. function openBwTestServerModal() {
  12818. fetchBwTestServerStatus();
  12819. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  12820. }
  12821. function closeBwTestServerModal() {
  12822. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  12823. }
  12824. async function submitBwTestServerSettings(e) {
  12825. e.preventDefault();
  12826. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  12827. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  12828. try {
  12829. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  12830. method: 'POST',
  12831. headers: { 'Content-Type': 'application/json' },
  12832. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  12833. });
  12834. if (!res.ok) {
  12835. const err = await res.json();
  12836. throw new Error(err.error || 'Failed to update server configuration');
  12837. }
  12838. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  12839. closeBwTestServerModal();
  12840. fetchBwTestServerStatus();
  12841. } catch (err) {
  12842. showToast('Server Configuration Error', err.message, 'error');
  12843. }
  12844. }
  12845. function setBwTestTarget(target) {
  12846. const inp = document.getElementById('bwtest-input-target');
  12847. if (inp) inp.value = target;
  12848. }
  12849. function setBwTestProtocol(proto) {
  12850. const hiddenInp = document.getElementById('bwtest-input-protocol');
  12851. if (hiddenInp) hiddenInp.value = proto;
  12852. const btnUdp = document.getElementById('bwtest-proto-udp');
  12853. const btnTcp = document.getElementById('bwtest-proto-tcp');
  12854. const badge = document.getElementById('bwtest-proto-badge');
  12855. const pktField = document.getElementById('bwtest-field-pktsize');
  12856. 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';
  12857. 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';
  12858. 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';
  12859. if (proto === 'udp') {
  12860. if (btnUdp) {
  12861. btnUdp.className = activeUdpCls;
  12862. const dot = btnUdp.querySelector('span');
  12863. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  12864. }
  12865. if (btnTcp) {
  12866. btnTcp.className = inactiveCls;
  12867. const dot = btnTcp.querySelector('span');
  12868. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12869. }
  12870. if (badge) {
  12871. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  12872. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  12873. }
  12874. if (pktField) pktField.classList.remove('opacity-40');
  12875. } else {
  12876. if (btnUdp) {
  12877. btnUdp.className = inactiveCls;
  12878. const dot = btnUdp.querySelector('span');
  12879. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12880. }
  12881. if (btnTcp) {
  12882. btnTcp.className = activeTcpCls;
  12883. const dot = btnTcp.querySelector('span');
  12884. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  12885. }
  12886. if (badge) {
  12887. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  12888. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  12889. }
  12890. if (pktField) pktField.classList.add('opacity-40');
  12891. }
  12892. }
  12893. function setBwTestDirection(dir) {
  12894. const hiddenInp = document.getElementById('bwtest-input-direction');
  12895. if (hiddenInp) hiddenInp.value = dir;
  12896. const btnBoth = document.getElementById('bwtest-dir-both');
  12897. const btnTx = document.getElementById('bwtest-dir-tx');
  12898. const btnRx = document.getElementById('bwtest-dir-rx');
  12899. 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';
  12900. 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';
  12901. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  12902. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  12903. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  12904. }
  12905. function setBwTestLimit(bps) {
  12906. const sel = document.getElementById('bwtest-input-limit');
  12907. if (sel) sel.value = String(bps);
  12908. }
  12909. async function checkActiveBwTest() {
  12910. try {
  12911. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  12912. if (!res.ok) return;
  12913. const st = await res.json();
  12914. if (st.running) {
  12915. setBwTestRunningUI(true);
  12916. if (st.current_sample) handleBwTestSample(st.current_sample);
  12917. startBwTestTelemetry();
  12918. }
  12919. } catch (err) {
  12920. console.error('Failed to check active BwTest:', err);
  12921. }
  12922. }
  12923. async function startBwTest(e) {
  12924. if (e && e.preventDefault) e.preventDefault();
  12925. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  12926. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  12927. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  12928. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  12929. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  12930. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  12931. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  12932. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  12933. bwtestState.targetDuration = duration;
  12934. bwtestState.chartPoints = [];
  12935. bwtestState.peakTx = 0;
  12936. bwtestState.peakRx = 0;
  12937. bwtestState.lastSampleIndex = 0;
  12938. // Clear UI elements
  12939. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  12940. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  12941. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  12942. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  12943. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  12944. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  12945. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  12946. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  12947. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  12948. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  12949. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  12950. const tbody = document.getElementById('bwtest-samples-tbody');
  12951. if (tbody) tbody.innerHTML = '';
  12952. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  12953. setBwTestRunningUI(true);
  12954. try {
  12955. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  12956. method: 'POST',
  12957. headers: { 'Content-Type': 'application/json' },
  12958. body: JSON.stringify({
  12959. target,
  12960. port,
  12961. direction,
  12962. protocol,
  12963. bandwidth_limit,
  12964. packet_size,
  12965. streams,
  12966. duration
  12967. })
  12968. });
  12969. if (!res.ok) {
  12970. const err = await res.json();
  12971. throw new Error(err.error || 'Failed to start bandwidth test');
  12972. }
  12973. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  12974. startBwTestTelemetry();
  12975. } catch (err) {
  12976. setBwTestRunningUI(false);
  12977. showToast('Start Failed', err.message, 'error');
  12978. }
  12979. }
  12980. function setBwTestRunningUI(running) {
  12981. bwtestState.running = running;
  12982. const startBtn = document.getElementById('bwtest-btn-start');
  12983. const stopBtn = document.getElementById('bwtest-btn-stop');
  12984. const badge = document.getElementById('bwtest-run-status-badge');
  12985. const ph = document.getElementById('bwtest-chart-placeholder');
  12986. if (running) {
  12987. if (startBtn) {
  12988. startBtn.disabled = true;
  12989. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  12990. }
  12991. if (stopBtn) {
  12992. stopBtn.disabled = false;
  12993. stopBtn.classList.remove('opacity-40');
  12994. }
  12995. if (badge) {
  12996. badge.innerText = 'TESTING...';
  12997. 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';
  12998. }
  12999. if (ph) ph.style.display = 'none';
  13000. } else {
  13001. if (startBtn) {
  13002. startBtn.disabled = false;
  13003. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13004. }
  13005. if (stopBtn) {
  13006. stopBtn.disabled = true;
  13007. stopBtn.classList.add('opacity-40');
  13008. }
  13009. if (badge) {
  13010. badge.innerText = 'IDLE';
  13011. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13012. }
  13013. }
  13014. }
  13015. async function stopBwTest() {
  13016. try {
  13017. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13018. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13019. } catch (err) {
  13020. console.error('Failed to stop test:', err);
  13021. }
  13022. }
  13023. function startBwTestTelemetry() {
  13024. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13025. bwtestState.pollTimer = setInterval(async () => {
  13026. try {
  13027. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13028. if (!res.ok) return;
  13029. const st = await res.json();
  13030. if (st.recent_samples && st.recent_samples.length > 0) {
  13031. // Process new samples
  13032. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13033. newSamples.forEach(s => handleBwTestSample(s));
  13034. bwtestState.lastSampleIndex = st.recent_samples.length;
  13035. }
  13036. if (!st.running) {
  13037. clearInterval(bwtestState.pollTimer);
  13038. bwtestState.pollTimer = null;
  13039. setBwTestRunningUI(false);
  13040. handleBwTestFinish(st.summary, st.error);
  13041. }
  13042. } catch (err) {
  13043. console.error('BwTest polling error:', err);
  13044. }
  13045. }, 400);
  13046. }
  13047. function handleBwTestSample(s) {
  13048. if (!s) return;
  13049. const txMbps = s.tx_mbps || 0;
  13050. const rxMbps = s.rx_mbps || 0;
  13051. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13052. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13053. // KPI updates
  13054. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13055. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13056. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13057. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13058. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13059. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13060. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13061. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13062. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13063. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13064. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13065. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13066. const elLoss = document.getElementById('bwtest-stat-loss');
  13067. if (elLoss) {
  13068. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13069. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13070. }
  13071. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13072. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13073. const elJitter = document.getElementById('bwtest-stat-jitter');
  13074. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13075. const elTime = document.getElementById('bwtest-stat-time');
  13076. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13077. const elData = document.getElementById('bwtest-stat-data');
  13078. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13079. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13080. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13081. // Append point to chart buffer
  13082. bwtestState.chartPoints.push({
  13083. elapsed: s.elapsed_sec || 0,
  13084. tx: txMbps,
  13085. rx: rxMbps
  13086. });
  13087. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13088. bwtestState.chartPoints.shift();
  13089. }
  13090. drawBwTestChart();
  13091. // Add row to breakdown table
  13092. const tbody = document.getElementById('bwtest-samples-tbody');
  13093. if (tbody) {
  13094. const tr = document.createElement('tr');
  13095. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13096. tr.innerHTML = `
  13097. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13098. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13099. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13100. <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>
  13101. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13102. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13103. `;
  13104. tbody.insertBefore(tr, tbody.firstChild);
  13105. const countEl = document.getElementById('bwtest-sample-count');
  13106. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13107. }
  13108. }
  13109. function handleBwTestFinish(summary, error) {
  13110. const badge = document.getElementById('bwtest-run-status-badge');
  13111. if (error) {
  13112. showToast('Benchmark Error', error, 'error');
  13113. if (badge) {
  13114. badge.innerText = 'ERROR';
  13115. 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';
  13116. }
  13117. } else if (summary) {
  13118. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13119. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13120. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13121. if (badge) {
  13122. badge.innerText = 'COMPLETED';
  13123. 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';
  13124. }
  13125. }
  13126. loadBwTestHistory();
  13127. fetchBwTestServerStatus();
  13128. }
  13129. function resizeBwTestCanvas() {
  13130. const canvas = document.getElementById('bwtest-chart');
  13131. if (!canvas || !canvas.parentElement) return;
  13132. const rect = canvas.parentElement.getBoundingClientRect();
  13133. const dpr = window.devicePixelRatio || 1;
  13134. canvas.width = rect.width * dpr;
  13135. canvas.height = rect.height * dpr;
  13136. const ctx = canvas.getContext('2d');
  13137. ctx.scale(dpr, dpr);
  13138. drawBwTestChart();
  13139. }
  13140. window.addEventListener('resize', () => {
  13141. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13142. });
  13143. function drawBwTestChart() {
  13144. const canvas = document.getElementById('bwtest-chart');
  13145. if (!canvas) return;
  13146. const ctx = canvas.getContext('2d');
  13147. const dpr = window.devicePixelRatio || 1;
  13148. const width = canvas.width / dpr;
  13149. const height = canvas.height / dpr;
  13150. ctx.clearRect(0, 0, width, height);
  13151. const points = bwtestState.chartPoints;
  13152. if (!points || points.length === 0) return;
  13153. // Determine scale ceiling
  13154. let maxRate = 10;
  13155. for (const p of points) {
  13156. if (p.tx > maxRate) maxRate = p.tx;
  13157. if (p.rx > maxRate) maxRate = p.rx;
  13158. }
  13159. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13160. const paddingLeft = 55;
  13161. const paddingBottom = 24;
  13162. const paddingTop = 12;
  13163. const paddingRight = 16;
  13164. const chartW = width - paddingLeft - paddingRight;
  13165. const chartH = height - paddingTop - paddingBottom;
  13166. // Grid Lines and Y-Axis labels
  13167. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13168. ctx.lineWidth = 1;
  13169. ctx.fillStyle = '#94a3b8';
  13170. ctx.font = '10px monospace';
  13171. ctx.textAlign = 'right';
  13172. const gridSteps = 4;
  13173. for (let i = 0; i <= gridSteps; i++) {
  13174. const val = (maxRate / gridSteps) * i;
  13175. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13176. ctx.beginPath();
  13177. ctx.moveTo(paddingLeft, y);
  13178. ctx.lineTo(width - paddingRight, y);
  13179. ctx.stroke();
  13180. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13181. }
  13182. // Draw TX Line (Cyan #22d3ee)
  13183. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13184. // Draw RX Line (Purple #a855f7)
  13185. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13186. }
  13187. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13188. if (points.length < 2) return;
  13189. const stepX = w / Math.max(points.length - 1, 1);
  13190. // Gradient area fill
  13191. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13192. grad.addColorStop(0, fillColor);
  13193. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13194. ctx.beginPath();
  13195. points.forEach((p, idx) => {
  13196. const x = left + idx * stepX;
  13197. const val = valFn(p);
  13198. const y = top + h - (val / maxVal) * h;
  13199. if (idx === 0) {
  13200. ctx.moveTo(x, y);
  13201. } else {
  13202. ctx.lineTo(x, y);
  13203. }
  13204. });
  13205. // Complete path for fill
  13206. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13207. ctx.lineTo(left, top + h);
  13208. ctx.closePath();
  13209. ctx.fillStyle = grad;
  13210. ctx.fill();
  13211. // Draw line stroke
  13212. ctx.beginPath();
  13213. ctx.lineWidth = 2.5;
  13214. ctx.strokeStyle = strokeColor;
  13215. points.forEach((p, idx) => {
  13216. const x = left + idx * stepX;
  13217. const val = valFn(p);
  13218. const y = top + h - (val / maxVal) * h;
  13219. if (idx === 0) {
  13220. ctx.moveTo(x, y);
  13221. } else {
  13222. ctx.lineTo(x, y);
  13223. }
  13224. });
  13225. ctx.stroke();
  13226. // Draw end point halo
  13227. const lastP = points[points.length - 1];
  13228. const lastX = left + (points.length - 1) * stepX;
  13229. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13230. ctx.fillStyle = strokeColor;
  13231. ctx.beginPath();
  13232. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13233. ctx.fill();
  13234. }
  13235. async function loadBwTestHistory() {
  13236. try {
  13237. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13238. if (!res.ok) return;
  13239. const list = await res.json();
  13240. renderBwTestHistory(Array.isArray(list) ? list : []);
  13241. } catch (err) {
  13242. console.error('Failed to load BwTest history:', err);
  13243. }
  13244. }
  13245. function renderBwTestHistory(list) {
  13246. const tbody = document.getElementById('bwtest-history-tbody');
  13247. if (!tbody) return;
  13248. if (list.length === 0) {
  13249. 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>`;
  13250. return;
  13251. }
  13252. tbody.innerHTML = '';
  13253. list.forEach(item => {
  13254. const s = item.summary || {};
  13255. const tr = document.createElement('tr');
  13256. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13257. const dirBadge = item.direction === 'both'
  13258. ? `<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>`
  13259. : item.direction === 'tx'
  13260. ? `<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>`
  13261. : `<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>`;
  13262. const protoBadge = item.protocol === 'tcp'
  13263. ? `<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>`
  13264. : `<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>`;
  13265. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13266. tr.innerHTML = `
  13267. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13268. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13269. <td class="py-2.5 px-4">${protoBadge}</td>
  13270. <td class="py-2.5 px-4">${dirBadge}</td>
  13271. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13272. <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>
  13273. <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>
  13274. <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>
  13275. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13276. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13277. `;
  13278. tbody.appendChild(tr);
  13279. });
  13280. }
  13281. // ======================== SETTINGS & ROUTER DNS ========================
  13282. state.settingsSubTab = 'dns';
  13283. state.dnsSettings = null;
  13284. state.dnsStaticRecords = [];
  13285. state.dnsStatus = null;
  13286. function switchSettingsSubTab(sub) {
  13287. state.settingsSubTab = sub;
  13288. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13289. const btnSys = document.getElementById('btn-settings-subtab-system');
  13290. const tabDns = document.getElementById('settings-subtab-dns');
  13291. const tabSys = document.getElementById('settings-subtab-system');
  13292. if (sub === 'dns') {
  13293. if (btnDns) {
  13294. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13295. }
  13296. if (btnSys) {
  13297. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13298. }
  13299. tabDns?.classList.remove('hidden');
  13300. tabSys?.classList.add('hidden');
  13301. loadDNSSettings();
  13302. } else {
  13303. if (btnSys) {
  13304. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13305. }
  13306. if (btnDns) {
  13307. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13308. }
  13309. tabSys?.classList.remove('hidden');
  13310. tabDns?.classList.add('hidden');
  13311. loadSystemSettings();
  13312. }
  13313. }
  13314. async function loadSettingsData(showLoading = false) {
  13315. if (state.settingsSubTab === 'system') {
  13316. await loadSystemSettings();
  13317. } else {
  13318. await loadDNSSettings();
  13319. }
  13320. }
  13321. async function loadDNSSettings() {
  13322. try {
  13323. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13324. fetch(`${API_BASE}/dns/settings`),
  13325. fetch(`${API_BASE}/dns/static`),
  13326. fetch(`${API_BASE}/dns/status`)
  13327. ]);
  13328. if (settingsRes.ok) {
  13329. state.dnsSettings = await settingsRes.json();
  13330. populateDNSSettingsForm(state.dnsSettings);
  13331. }
  13332. if (staticRes.ok) {
  13333. state.dnsStaticRecords = await staticRes.json();
  13334. renderStaticDNSList();
  13335. }
  13336. if (statusRes.ok) {
  13337. state.dnsStatus = await statusRes.json();
  13338. updateDNSStatusView(state.dnsStatus);
  13339. }
  13340. } catch (err) {
  13341. console.error('Failed to load DNS settings:', err);
  13342. }
  13343. }
  13344. function populateDNSSettingsForm(s) {
  13345. if (!s) return;
  13346. const serversInput = document.getElementById('dns-servers-input');
  13347. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13348. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13349. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13350. const domainInput = document.getElementById('dns-domain-input');
  13351. if (domainInput) domainInput.value = s.domain || '';
  13352. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13353. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13354. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13355. if (dynamicEl) {
  13356. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13357. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13358. } else {
  13359. dynamicEl.innerText = 'None';
  13360. }
  13361. }
  13362. }
  13363. function updateDNSStatusView(st) {
  13364. if (!st) return;
  13365. const preview = document.getElementById('dns-resolv-preview');
  13366. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13367. const pillText = document.getElementById('dns-live-status-text');
  13368. const pill = document.getElementById('dns-live-status-pill');
  13369. if (pill && pillText) {
  13370. if (st.service_running) {
  13371. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  13372. pillText.innerText = 'DNS Service Active';
  13373. } else {
  13374. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  13375. pillText.innerText = 'DNS Service Inactive';
  13376. }
  13377. }
  13378. }
  13379. function appendDNSPreset(preset) {
  13380. const input = document.getElementById('dns-servers-input');
  13381. if (!input) return;
  13382. const current = input.value.trim();
  13383. if (!current) {
  13384. input.value = preset;
  13385. } else {
  13386. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13387. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13388. toAdd.forEach(ip => {
  13389. if (!existing.includes(ip)) existing.push(ip);
  13390. });
  13391. input.value = existing.join(', ');
  13392. }
  13393. }
  13394. async function saveDNSSettings(e) {
  13395. e.preventDefault();
  13396. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13397. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13398. if (servers.length === 0) {
  13399. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13400. return;
  13401. }
  13402. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13403. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13404. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13405. try {
  13406. const res = await fetch(`${API_BASE}/dns/settings`, {
  13407. method: 'POST',
  13408. headers: { 'Content-Type': 'application/json' },
  13409. body: JSON.stringify({
  13410. servers: servers,
  13411. cache_size: cacheSize,
  13412. domain: domain,
  13413. allow_remote_requests: allowRemote
  13414. })
  13415. });
  13416. const data = await res.json();
  13417. if (res.ok) {
  13418. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13419. loadDNSSettings();
  13420. } else {
  13421. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13422. }
  13423. } catch (err) {
  13424. showToast('Error', err.message, 'error');
  13425. }
  13426. }
  13427. async function flushDNSCache() {
  13428. try {
  13429. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13430. if (res.ok) {
  13431. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13432. loadDNSSettings();
  13433. } else {
  13434. const err = await res.json();
  13435. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13436. }
  13437. } catch (err) {
  13438. showToast('Error', err.message, 'error');
  13439. }
  13440. }
  13441. function renderStaticDNSList() {
  13442. const tbody = document.getElementById('dns-static-tbody');
  13443. const empty = document.getElementById('dns-static-empty');
  13444. const badge = document.getElementById('dns-static-count-badge');
  13445. if (!tbody) return;
  13446. tbody.innerHTML = '';
  13447. const records = state.dnsStaticRecords || [];
  13448. if (badge) badge.innerText = `${records.length} Records`;
  13449. if (records.length === 0) {
  13450. empty?.classList.remove('hidden');
  13451. return;
  13452. }
  13453. empty?.classList.add('hidden');
  13454. records.forEach(rec => {
  13455. const tr = document.createElement('tr');
  13456. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  13457. tr.innerHTML = `
  13458. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  13459. <td class="py-2.5 px-4">
  13460. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  13461. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  13462. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  13463. }">
  13464. ${rec.type || 'A'}
  13465. </span>
  13466. </td>
  13467. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  13468. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  13469. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  13470. <td class="py-2.5 px-4">
  13471. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  13472. ${rec.disabled ? 'Disabled' : 'Active'}
  13473. </span>
  13474. </td>
  13475. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  13476. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  13477. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  13478. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  13479. </td>
  13480. `;
  13481. tbody.appendChild(tr);
  13482. });
  13483. }
  13484. function openStaticDNSModal(id = null) {
  13485. const modal = document.getElementById('modal-static-dns');
  13486. const title = document.getElementById('modal-static-dns-title');
  13487. const form = document.getElementById('form-static-dns');
  13488. if (!modal || !form) return;
  13489. form.reset();
  13490. document.getElementById('modal-static-dns-id').value = '';
  13491. if (id) {
  13492. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  13493. if (rec) {
  13494. if (title) title.innerText = 'Edit Static DNS Record';
  13495. document.getElementById('modal-static-dns-id').value = rec.id;
  13496. document.getElementById('modal-static-dns-name').value = rec.name;
  13497. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  13498. document.getElementById('modal-static-dns-addr').value = rec.address;
  13499. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  13500. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  13501. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  13502. }
  13503. } else {
  13504. if (title) title.innerText = 'Add Static DNS Record';
  13505. }
  13506. modal.classList.remove('hidden');
  13507. }
  13508. function closeStaticDNSModal() {
  13509. document.getElementById('modal-static-dns')?.classList.add('hidden');
  13510. }
  13511. async function submitSaveStaticDNS(e) {
  13512. e.preventDefault();
  13513. const id = document.getElementById('modal-static-dns-id')?.value || '';
  13514. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  13515. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  13516. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  13517. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  13518. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  13519. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  13520. if (!name || !address) {
  13521. showToast('Validation Error', 'Name and Target Address are required', 'error');
  13522. return;
  13523. }
  13524. try {
  13525. const res = await fetch(`${API_BASE}/dns/static`, {
  13526. method: 'POST',
  13527. headers: { 'Content-Type': 'application/json' },
  13528. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  13529. });
  13530. const data = await res.json();
  13531. if (res.ok) {
  13532. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  13533. closeStaticDNSModal();
  13534. loadDNSSettings();
  13535. } else {
  13536. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  13537. }
  13538. } catch (err) {
  13539. showToast('Error', err.message, 'error');
  13540. }
  13541. }
  13542. async function deleteStaticDNS(id) {
  13543. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  13544. try {
  13545. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13546. if (res.ok) {
  13547. showToast('Deleted', 'Static DNS record deleted', 'success');
  13548. loadDNSSettings();
  13549. }
  13550. } catch (err) {
  13551. showToast('Error', err.message, 'error');
  13552. }
  13553. }
  13554. async function toggleStaticDNS(id, disabled) {
  13555. try {
  13556. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  13557. method: 'POST',
  13558. headers: { 'Content-Type': 'application/json' },
  13559. body: JSON.stringify({ disabled })
  13560. });
  13561. if (res.ok) {
  13562. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  13563. loadDNSSettings();
  13564. }
  13565. } catch (err) {
  13566. showToast('Error', err.message, 'error');
  13567. }
  13568. }
  13569. async function loadSystemSettings() {
  13570. try {
  13571. const res = await fetch(`${API_BASE}/system/settings`);
  13572. if (res.ok) {
  13573. const data = await res.json();
  13574. const hostInput = document.getElementById('system-hostname-input');
  13575. if (hostInput) hostInput.value = data.hostname || '';
  13576. const tzInput = document.getElementById('system-timezone-input');
  13577. if (tzInput && data.timezone) tzInput.value = data.timezone;
  13578. }
  13579. } catch (err) {
  13580. console.error('Failed to load system settings:', err);
  13581. }
  13582. }
  13583. async function saveSystemSettings(e) {
  13584. e.preventDefault();
  13585. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  13586. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  13587. try {
  13588. const res = await fetch(`${API_BASE}/system/settings`, {
  13589. method: 'POST',
  13590. headers: { 'Content-Type': 'application/json' },
  13591. body: JSON.stringify({ hostname, timezone })
  13592. });
  13593. const data = await res.json();
  13594. if (res.ok) {
  13595. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  13596. const sideH = document.getElementById('side-hostname');
  13597. if (sideH) sideH.innerText = data.hostname;
  13598. } else {
  13599. showToast('Error', data.error || 'Failed to save system settings', 'error');
  13600. }
  13601. } catch (err) {
  13602. showToast('Error', err.message, 'error');
  13603. }
  13604. }