app.js 518 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371
  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. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. 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';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. 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';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  108. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  109. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  110. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  111. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  112. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  113. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  114. };
  115. const header = titles[tabName] || titles.dashboard;
  116. const pTitle = document.getElementById('page-title');
  117. if (pTitle) pTitle.innerText = header.title;
  118. const pSub = document.getElementById('page-subtitle');
  119. if (pSub) pSub.innerText = header.sub;
  120. // Toggle sections dynamically for all section elements
  121. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  122. if (el.id === `section-${tabName}`) {
  123. el.classList.remove('hidden');
  124. } else {
  125. el.classList.add('hidden');
  126. }
  127. });
  128. if (tabName === 'bridge') loadBridge();
  129. if (tabName === 'firewall') loadFirewall();
  130. if (tabName === 'routes') loadRoutes();
  131. if (tabName === 'bgp') {
  132. loadDynamicRouting();
  133. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  134. }
  135. if (tabName === 'ospf') {
  136. loadDynamicRouting();
  137. switchOspfTab(state.activeOspfTab || 'instances');
  138. }
  139. if (tabName === 'routing-filters') loadDynamicRouting();
  140. if (tabName === 'dynamic-routing') loadDynamicRouting();
  141. if (tabName === 'ppp') loadPPP();
  142. if (tabName === 'eoip') loadEoIP();
  143. if (tabName === 'persistence') loadDebianConfig();
  144. if (tabName === 'pppoe') loadPPPoE();
  145. if (tabName === 'wireguard') loadWireGuard();
  146. if (tabName === 'ipsec') loadIPSec();
  147. if (tabName === 'l2tp') loadL2TP();
  148. if (tabName === 'pptp') loadPPTP();
  149. if (tabName === 'tools') loadToolsView();
  150. if (tabName === 'dhcp-client') loadDHCPClients();
  151. setTimeout(initTableSorting, 50);
  152. }
  153. // Fetch all core system, network and VPN telemetry
  154. async function fetchData(isManual = false) {
  155. const spinner = document.getElementById('refresh-spinner');
  156. if (isManual && spinner) spinner.classList.add('animate-spin');
  157. try {
  158. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  159. fetch(`${API_BASE}/system/status`),
  160. fetch(`${API_BASE}/interfaces`),
  161. fetch(`${API_BASE}/vlans`),
  162. fetch(`${API_BASE}/vpn/status`),
  163. fetch(`${API_BASE}/firewall/summary`),
  164. fetch(`${API_BASE}/routing/dynamic/summary`),
  165. fetch(`${API_BASE}/bridge/summary`),
  166. fetch(`${API_BASE}/dhcp/clients/summary`),
  167. fetch(`${API_BASE}/dhcp/clients`)
  168. ]);
  169. if (dhcpSumRes && dhcpSumRes.ok) {
  170. state.dhcpSummary = await dhcpSumRes.json();
  171. const bDhcp = document.getElementById('badge-dhcp-client-count');
  172. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  173. }
  174. if (dhcpClientsRes && dhcpClientsRes.ok) {
  175. state.dhcpClients = await dhcpClientsRes.json();
  176. }
  177. if (brSummaryRes.ok) {
  178. state.bridgeSummary = await brSummaryRes.json();
  179. const bBridge = document.getElementById('badge-bridge-count');
  180. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sBr = document.getElementById('bridge-stat-bridges');
  182. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sPorts = document.getElementById('bridge-stat-ports');
  184. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  185. const sHosts = document.getElementById('bridge-stat-hosts');
  186. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  187. }
  188. if (statusRes.ok) state.systemStatus = await statusRes.json();
  189. if (ifacesRes.ok) {
  190. const ifacesData = await ifacesRes.json();
  191. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  192. state.interfaces = rawIfaces.filter(i => {
  193. if (!i.name) return false;
  194. if (i.name.startsWith('ep_')) return false;
  195. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  196. });
  197. try { populateToolsInterfaces(); } catch (e) {}
  198. }
  199. if (vlansRes.ok) {
  200. const vlansData = await vlansRes.json();
  201. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  202. }
  203. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  204. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  205. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  206. updateSystemMetrics();
  207. updateBadges();
  208. if (state.activeTab === 'dashboard') renderDashboard();
  209. if (state.activeTab === 'interfaces') renderInterfacesList();
  210. if (state.activeTab === 'vlans') renderVlansList();
  211. if (state.activeTab === 'firewall') loadFirewall(false);
  212. if (state.activeTab === 'routes') loadRoutes(false);
  213. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  214. if (state.activeTab === 'ppp') loadPPP(false);
  215. if (state.activeTab === 'eoip') loadEoIP(false);
  216. if (state.activeTab === 'pppoe') loadPPPoE(false);
  217. if (state.activeTab === 'wireguard') loadWireGuard(false);
  218. if (state.activeTab === 'ipsec') loadIPSec(false);
  219. if (state.activeTab === 'l2tp') loadL2TP(false);
  220. if (state.activeTab === 'pptp') loadPPTP(false);
  221. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  222. } catch (err) {
  223. console.error('Failed to fetch router state:', err);
  224. } finally {
  225. if (isManual && spinner) {
  226. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  227. }
  228. }
  229. }
  230. // Update Top KPI and Sidebar Telemetry
  231. function updateSystemMetrics() {
  232. const s = state.systemStatus;
  233. const v = state.vpnStatus;
  234. if (!s) return;
  235. // Sidebar Host & Uptime
  236. const sideHost = document.getElementById('side-hostname');
  237. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  238. const sideUp = document.getElementById('side-uptime');
  239. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  240. const sideGw = document.getElementById('side-gateway-ip');
  241. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  242. // Compute CPU Metrics
  243. let cpuPct = 0;
  244. if (s.cpu_pct !== undefined) {
  245. cpuPct = s.cpu_pct;
  246. } else if (s.cpu_load && s.cpu_load.length > 0) {
  247. const cores = s.cpu_cores || 1;
  248. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  249. }
  250. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  251. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  252. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  253. // Sidebar CPU
  254. const sideCpuVal = document.getElementById('side-cpu-val');
  255. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  256. const sideCpuBar = document.getElementById('side-cpu-bar');
  257. if (sideCpuBar) {
  258. sideCpuBar.style.width = cpuWidth;
  259. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  260. }
  261. // Dashboard CPU Card
  262. const dashCpuVal = document.getElementById('dash-cpu-val');
  263. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  264. const dashCpuBar = document.getElementById('dash-cpu-bar');
  265. if (dashCpuBar) {
  266. dashCpuBar.style.width = cpuWidth;
  267. if (cpuPct > 85) {
  268. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  269. } else if (cpuPct > 65) {
  270. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  271. } else {
  272. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  273. }
  274. }
  275. const dashCpuCores = document.getElementById('dash-cpu-cores');
  276. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  277. const dashCpuLoad = document.getElementById('dash-cpu-load');
  278. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  279. const dashCpuStatus = document.getElementById('dash-cpu-status');
  280. if (dashCpuStatus) {
  281. if (cpuPct > 85) {
  282. dashCpuStatus.innerText = 'High';
  283. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  284. } else if (cpuPct > 65) {
  285. dashCpuStatus.innerText = 'Heavy';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  287. } else {
  288. dashCpuStatus.innerText = 'Normal';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  290. }
  291. }
  292. // Compute RAM Metrics
  293. const memPct = Math.round(s.mem_usage_pct || 0);
  294. const memPctStr = `${memPct}%`;
  295. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  296. const usedMB = s.mem_used_mb || 0;
  297. const totalMB = s.mem_total_mb || 0;
  298. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  299. function fmtMemMB(mb) {
  300. if (mb >= 1024) {
  301. return `${(mb / 1024).toFixed(1)} GB`;
  302. }
  303. return `${mb} MB`;
  304. }
  305. // Sidebar RAM
  306. const sideRamVal = document.getElementById('side-ram-val');
  307. if (sideRamVal) sideRamVal.innerText = memPctStr;
  308. const sideRamBar = document.getElementById('side-ram-bar');
  309. if (sideRamBar) sideRamBar.style.width = memWidth;
  310. // Dashboard RAM Card
  311. const dashRamVal = document.getElementById('dash-ram-val');
  312. if (dashRamVal) dashRamVal.innerText = memPctStr;
  313. const dashRamBar = document.getElementById('dash-ram-bar');
  314. if (dashRamBar) {
  315. dashRamBar.style.width = memWidth;
  316. if (memPct > 85) {
  317. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  318. } else if (memPct > 70) {
  319. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  320. } else {
  321. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  322. }
  323. }
  324. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  325. if (dashRamUsedTotal) {
  326. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  327. }
  328. const dashRamFree = document.getElementById('dash-ram-free');
  329. if (dashRamFree) {
  330. dashRamFree.innerText = fmtMemMB(freeMB);
  331. }
  332. const dashRamStatus = document.getElementById('dash-ram-status');
  333. if (dashRamStatus) {
  334. if (memPct > 85) {
  335. dashRamStatus.innerText = 'High';
  336. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  337. } else {
  338. dashRamStatus.innerText = 'Active';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  340. }
  341. }
  342. // Legacy Dashboard Stats (Safe checks)
  343. const elIfacesUp = document.getElementById('stat-ifaces-up');
  344. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  345. const elIfacesTot = document.getElementById('stat-ifaces-total');
  346. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  347. const elIfacesDown = document.getElementById('stat-ifaces-down');
  348. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  349. const elVlans = document.getElementById('stat-vlans-count');
  350. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  351. // VPN Status Indicators
  352. if (v) {
  353. const totalActive = v.total_active_tunnels || 0;
  354. const statVpnActive = document.getElementById('stat-vpn-active');
  355. if (statVpnActive) statVpnActive.innerText = totalActive;
  356. const tunnelsDot = document.getElementById('tunnels-dot');
  357. const tunnelsLabel = document.getElementById('tunnels-label');
  358. if (tunnelsDot && tunnelsLabel) {
  359. if (totalActive > 0) {
  360. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  361. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  362. } else {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  364. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  365. }
  366. }
  367. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  368. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  369. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  370. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  371. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  372. }
  373. // Total Live Bandwidth Rate
  374. let totalRx = 0;
  375. let totalTx = 0;
  376. (state.interfaces || []).forEach(i => {
  377. if (i.rate) {
  378. totalRx += i.rate.rx_bytes_sec || 0;
  379. totalTx += i.rate.tx_bytes_sec || 0;
  380. }
  381. });
  382. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  383. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  384. }
  385. function setDotBadge(id, active) {
  386. const el = document.getElementById(id);
  387. if (!el) return;
  388. if (active) {
  389. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  390. } else {
  391. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  392. }
  393. }
  394. function updateBadges() {
  395. const bIfaces = document.getElementById('badge-ifaces-count');
  396. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  397. const bVlans = document.getElementById('badge-vlans-count');
  398. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  399. if (state.fwSummary) {
  400. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  401. const badgeFw = document.getElementById('badge-firewall-count');
  402. if (badgeFw) badgeFw.innerText = totalFwRules;
  403. }
  404. if (state.vpnStatus) {
  405. const v = state.vpnStatus;
  406. const bEoIP = document.getElementById('badge-eoip-count');
  407. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  408. const bPPPSess = document.getElementById('badge-ppp-sessions');
  409. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  410. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  411. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  412. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  413. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  414. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  415. }
  416. if (state.dynSummary) {
  417. const d = state.dynSummary;
  418. setDotBadge('badge-bgp-dot', d.bgp_running);
  419. setDotBadge('badge-ospf-dot', d.ospf_running);
  420. const bBgp = document.getElementById('badge-bgp-count');
  421. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  422. const bOspf = document.getElementById('badge-ospf-count');
  423. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  424. const bFilters = document.getElementById('badge-filters-count');
  425. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  426. }
  427. }
  428. // Render Dashboard View
  429. function renderDashboard() {
  430. const matrix = document.getElementById('port-matrix');
  431. matrix.innerHTML = '';
  432. (state.interfaces || []).forEach(iface => {
  433. const isUp = iface.state === 'UP';
  434. const isVlan = iface.is_vlan;
  435. const portCard = document.createElement('div');
  436. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  437. isUp
  438. ? (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')
  439. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  440. }`;
  441. portCard.onclick = () => openIfaceModal(iface.name);
  442. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  443. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  444. portCard.innerHTML = `
  445. <div class="flex items-center justify-between mb-2">
  446. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  447. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  448. </div>
  449. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  450. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  451. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  452. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  453. </div>
  454. `;
  455. matrix.appendChild(portCard);
  456. });
  457. const ifaceTbody = document.getElementById('quick-interfaces-table');
  458. if (ifaceTbody) {
  459. ifaceTbody.innerHTML = '';
  460. (state.interfaces || []).forEach(i => {
  461. const isUp = i.state === 'UP';
  462. const tr = document.createElement('tr');
  463. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  464. tr.onclick = () => openIfaceModal(i.name);
  465. const rxStr = i.rate?.rx_human || '0 B/s';
  466. const txStr = i.rate?.tx_human || '0 B/s';
  467. tr.innerHTML = `
  468. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  469. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  470. <span>${i.name}</span>
  471. </td>
  472. <td class="py-2.5 text-slate-300 font-sans">
  473. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  474. </td>
  475. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  476. <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>
  477. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  478. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  479. </td>
  480. <td class="py-2.5 text-right font-sans font-semibold">
  481. <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>
  482. </td>
  483. `;
  484. ifaceTbody.appendChild(tr);
  485. });
  486. }
  487. const vlanTbody = document.getElementById('quick-vlans-table');
  488. if (vlanTbody) {
  489. vlanTbody.innerHTML = '';
  490. }
  491. }
  492. // Expand / Collapse Handlers
  493. function toggleExpand(parentName) {
  494. if (state.expandedParents.has(parentName)) {
  495. state.expandedParents.delete(parentName);
  496. } else {
  497. state.expandedParents.add(parentName);
  498. }
  499. renderInterfacesList();
  500. }
  501. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  502. function supportsVLAN(iface) {
  503. if (!iface) return false;
  504. if (iface.is_vlan) return false;
  505. const name = (iface.name || '').toLowerCase();
  506. const type = (iface.type || '').toLowerCase();
  507. const role = (iface.role || '').toLowerCase();
  508. // Exclude loopback
  509. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  510. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  511. if (type === 'wireguard' || name.startsWith('wg')) return false;
  512. // Exclude PPP / PPPoE
  513. if (type === 'ppp' || name.startsWith('ppp')) return false;
  514. // Exclude other Layer 3 tunnels and dummy devices
  515. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  516. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  517. return false;
  518. }
  519. // If name already contains a dot, it's already a sub-interface
  520. if (name.includes('.')) return false;
  521. return true;
  522. }
  523. // Expand / Collapse Handlers
  524. function toggleExpand(parentName) {
  525. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  526. if (childVlans.length === 0) {
  527. // Cannot expand an interface with no VLANs
  528. state.expandedParents.delete(parentName);
  529. return;
  530. }
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. function expandAllIfaces(expand) {
  539. if (expand) {
  540. (state.interfaces || []).forEach(i => {
  541. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  542. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  543. });
  544. } else {
  545. state.expandedParents.clear();
  546. }
  547. renderInterfacesList();
  548. }
  549. // Filter and Render Hierarchical Interfaces List
  550. function filterIfaces(filter) {
  551. state.ifaceFilter = filter || 'all';
  552. renderInterfacesList();
  553. }
  554. function renderInterfacesList() {
  555. const tbody = document.getElementById('interfaces-tree-tbody');
  556. const emptyState = document.getElementById('interfaces-empty-state');
  557. const summary = document.getElementById('ifaces-list-summary');
  558. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  559. tbody.innerHTML = '';
  560. const allIfaces = state.interfaces || [];
  561. const allVlans = state.vlans || [];
  562. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  563. const filteredParents = parentIfaces.filter(parent => {
  564. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  565. if (query) {
  566. const matchName = parent.name.toLowerCase().includes(query);
  567. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  568. const matchRole = (parent.role || '').toLowerCase().includes(query);
  569. const matchType = (parent.type || '').toLowerCase().includes(query);
  570. const matchVlan = childVlans.some(v =>
  571. v.name.toLowerCase().includes(query) ||
  572. String(v.vlan_id).includes(query) ||
  573. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  574. (v.description || '').toLowerCase().includes(query)
  575. );
  576. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  577. }
  578. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  579. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  580. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  581. return true;
  582. });
  583. if (summary) {
  584. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  585. }
  586. if (filteredParents.length === 0) {
  587. emptyState?.classList.remove('hidden');
  588. return;
  589. }
  590. emptyState?.classList.add('hidden');
  591. filteredParents.forEach(parent => {
  592. const isUp = parent.state === 'UP';
  593. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  594. const hasVlans = childVlans.length > 0;
  595. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  596. const canHaveVlan = supportsVLAN(parent);
  597. const parentRow = document.createElement('tr');
  598. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  599. parentRow.innerHTML = `
  600. <td class="py-3 px-3 text-center">
  601. ${hasVlans ? `
  602. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  603. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  604. <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">
  605. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  606. </svg>
  607. </button>
  608. ` : `
  609. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  610. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  611. </div>
  612. `}
  613. </td>
  614. <td class="py-3 px-4">
  615. <div class="flex items-center space-x-2.5">
  616. <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">
  617. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  618. </div>
  619. <div>
  620. <div class="flex items-center gap-2">
  621. ${hasVlans ? `
  622. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  623. <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>
  624. ` : `
  625. <span class="font-bold text-white text-sm">${parent.name}</span>
  626. <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>
  627. `}
  628. </div>
  629. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  630. </div>
  631. </div>
  632. </td>
  633. <td class="py-3 px-4 font-sans">
  634. <div class="flex items-center gap-1.5">
  635. <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>
  636. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  637. </div>
  638. </td>
  639. <td class="py-3 px-4">
  640. ${parent.ipv4 && parent.ipv4.length > 0
  641. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  642. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  643. }
  644. ${(() => {
  645. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  646. if (!c) return '';
  647. 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');
  648. 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>`;
  649. })()}
  650. </td>
  651. <td class="py-3 px-4 text-slate-400 text-[11px]">
  652. <div>${parent.mac || 'N/A'}</div>
  653. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  654. </td>
  655. <td class="py-3 px-4 text-[11px]">
  656. <div class="flex items-center space-x-2">
  657. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  658. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  659. </div>
  660. </td>
  661. <td class="py-3 px-4 font-sans">
  662. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  663. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  664. 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'
  665. }" title="Click to toggle link status">
  666. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  667. <span>${parent.state}</span>
  668. </button>
  669. </td>
  670. <td class="py-3 px-4 text-right space-x-2 font-sans">
  671. ${(() => {
  672. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  673. if (c) {
  674. 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>`;
  675. }
  676. 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>`;
  677. })()}
  678. ${canHaveVlan ? `
  679. <button onclick="openVlanModal('${parent.name}')"
  680. 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">
  681. + Add VLAN
  682. </button>
  683. ` : ''}
  684. <button onclick="openIfaceModal('${parent.name}')"
  685. 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">
  686. Configure
  687. </button>
  688. </td>
  689. `;
  690. tbody.appendChild(parentRow);
  691. if (isExpanded) {
  692. const drawerRow = document.createElement('tr');
  693. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  694. const drawerCell = document.createElement('td');
  695. drawerCell.colSpan = 8;
  696. drawerCell.className = 'p-0';
  697. drawerCell.innerHTML = `
  698. <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">
  699. <div class="flex items-center justify-between mb-3">
  700. <div class="flex items-center space-x-3">
  701. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  702. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  703. </span>
  704. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  705. ${childVlans.length} Attached
  706. </span>
  707. </div>
  708. <button onclick="openVlanModal('${parent.name}')"
  709. 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">
  710. <span>+ Create VLAN on ${parent.name}</span>
  711. </button>
  712. </div>
  713. ${childVlans.length === 0 ? `
  714. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  715. <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>
  716. <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">
  717. <span>+ Create Your First VLAN on ${parent.name}</span>
  718. </button>
  719. </div>
  720. ` : `
  721. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  722. <table class="w-full text-left text-xs font-mono">
  723. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  724. <tr>
  725. <th class="py-2.5 px-4">VLAN ID</th>
  726. <th class="py-2.5 px-4">Interface Device</th>
  727. <th class="py-2.5 px-4">Subnet Gateway</th>
  728. <th class="py-2.5 px-4">Role / Alias</th>
  729. <th class="py-2.5 px-4">MTU</th>
  730. <th class="py-2.5 px-4">Throughput</th>
  731. <th class="py-2.5 px-4">Status</th>
  732. <th class="py-2.5 px-4 text-right">Actions</th>
  733. </tr>
  734. </thead>
  735. <tbody class="divide-y divide-slate-800/70">
  736. ${childVlans.map(v => {
  737. const isVlanUp = v.state === 'UP';
  738. return `
  739. <tr class="hover:bg-slate-800/40 transition">
  740. <td class="py-2.5 px-4">
  741. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  742. VLAN ${v.vlan_id}
  743. </span>
  744. </td>
  745. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  746. <span class="text-cyan-500">└─</span>
  747. <span>${v.name}</span>
  748. </td>
  749. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  750. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  751. ${(() => {
  752. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  753. if (!c) return '';
  754. 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';
  755. 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>`;
  756. })()}
  757. </td>
  758. <td class="py-2.5 px-4 font-sans text-slate-300">
  759. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  760. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  763. <td class="py-2.5 px-4 text-[11px]">
  764. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  765. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 font-sans">
  768. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  769. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  770. 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'
  771. }">
  772. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  773. <span>${v.state}</span>
  774. </button>
  775. </td>
  776. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (c) {
  780. 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>`;
  781. }
  782. 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>`;
  783. })()}
  784. <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>
  785. <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>
  786. </td>
  787. </tr>
  788. `;
  789. }).join('')}
  790. </tbody>
  791. </table>
  792. </div>
  793. `}
  794. </div>
  795. `;
  796. drawerRow.appendChild(drawerCell);
  797. tbody.appendChild(drawerRow);
  798. }
  799. });
  800. }
  801. // Render VLANs Dedicated View
  802. function renderVlansList() {
  803. const tbody = document.getElementById('vlans-table-body');
  804. if (!tbody) return;
  805. const emptyState = document.getElementById('vlans-empty-state');
  806. const countBadge = document.getElementById('vlans-table-count');
  807. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  808. tbody.innerHTML = '';
  809. const allVlans = state.vlans || [];
  810. if (countBadge) countBadge.innerText = allVlans.length;
  811. const filtered = allVlans.filter(v => {
  812. if (!query) return true;
  813. return v.name.toLowerCase().includes(query) ||
  814. String(v.vlan_id).includes(query) ||
  815. (v.description || '').toLowerCase().includes(query) ||
  816. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  817. });
  818. if (allVlans.length === 0) {
  819. emptyState.classList.remove('hidden');
  820. return;
  821. }
  822. emptyState.classList.add('hidden');
  823. filtered.forEach(v => {
  824. const isUp = v.state === 'UP';
  825. const tr = document.createElement('tr');
  826. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  827. tr.innerHTML = `
  828. <td class="py-3 px-4">
  829. <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">
  830. VLAN ${v.vlan_id}
  831. </span>
  832. </td>
  833. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  834. <td class="py-3 px-4 text-slate-300">
  835. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  836. </td>
  837. <td class="py-3 px-4 text-emerald-400 font-medium">
  838. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  839. </td>
  840. <td class="py-3 px-4 text-slate-300 font-sans">
  841. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  842. </td>
  843. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  844. <td class="py-3 px-4 font-sans">
  845. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  846. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  847. 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'
  848. }">
  849. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  850. <span>${v.state}</span>
  851. </button>
  852. </td>
  853. <td class="py-3 px-4 text-right space-x-2 font-sans">
  854. <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>
  855. <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>
  856. </td>
  857. `;
  858. tbody.appendChild(tr);
  859. });
  860. }
  861. // Toggle interface UP / DOWN
  862. async function toggleInterfaceState(name, newState) {
  863. try {
  864. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  865. method: 'POST',
  866. headers: { 'Content-Type': 'application/json' },
  867. body: JSON.stringify({ state: newState })
  868. });
  869. const data = await res.json();
  870. if (res.ok) {
  871. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  872. fetchData(false);
  873. } else {
  874. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  875. }
  876. } catch (err) {
  877. showToast('Error', err.message, 'error');
  878. }
  879. }
  880. // ---------------- MikroTik Flag & Utilities ----------------
  881. function renderMikroTikFlag(running, disabled) {
  882. if (running) {
  883. 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>`;
  884. }
  885. if (disabled) {
  886. 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>`;
  887. }
  888. 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>`;
  889. }
  890. function copyToClipboard(text, label = 'Text') {
  891. navigator.clipboard.writeText(text).then(() => {
  892. showToast('Copied', `${label} copied to clipboard`, 'success');
  893. }).catch(() => {
  894. prompt('Copy value:', text);
  895. });
  896. }
  897. // ======================== PPP Profiles Shared Helper ========================
  898. async function fetchPPPProfilesList() {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  901. if (res.ok) {
  902. state.pppProfiles = await res.json();
  903. }
  904. } catch (err) {
  905. console.error('Failed to load PPP profiles:', err);
  906. }
  907. }
  908. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  909. const sel = document.getElementById(selectId);
  910. if (!sel) return;
  911. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  912. { name: 'default', use_encryption: 'no' },
  913. { name: 'default-encryption', use_encryption: 'required' }
  914. ];
  915. sel.innerHTML = '';
  916. profiles.forEach(p => {
  917. const opt = document.createElement('option');
  918. opt.value = p.name;
  919. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  920. opt.innerText = `${p.name}${encBadge}`;
  921. sel.appendChild(opt);
  922. });
  923. if (selectedVal) {
  924. sel.value = selectedVal;
  925. } else {
  926. sel.value = defaultVal;
  927. }
  928. if (!sel.value && sel.options.length > 0) {
  929. sel.selectedIndex = 0;
  930. }
  931. }
  932. // ======================== PPPoE Multi-Instance ========================
  933. async function loadPPPoE(populateInputs = true) {
  934. try {
  935. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  936. await fetchPPPProfilesList();
  937. }
  938. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  939. const list = await res.json();
  940. state.pppoeList = Array.isArray(list) ? list : [];
  941. const badge = document.getElementById('pppoe-count-badge');
  942. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  943. const tbody = document.getElementById('pppoe-table-body');
  944. const empty = document.getElementById('pppoe-empty');
  945. if (!tbody) return;
  946. tbody.innerHTML = '';
  947. if (state.pppoeList.length === 0) {
  948. if (empty) empty.classList.remove('hidden');
  949. } else {
  950. if (empty) empty.classList.add('hidden');
  951. state.pppoeList.forEach(inst => {
  952. const tr = document.createElement('tr');
  953. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  954. tr.innerHTML = `
  955. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  956. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  957. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  958. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  959. <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>
  960. <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>
  961. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  962. <td class="py-2.5 px-3 text-center">
  963. <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'}">
  964. ${inst.default_route ? 'Yes' : 'No'}
  965. </span>
  966. </td>
  967. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  968. ${inst.running ? `
  969. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  970. ` : `
  971. <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>
  972. `}
  973. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  974. ${inst.disabled ? 'Enable' : 'Disable'}
  975. </button>
  976. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  977. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  978. </td>
  979. `;
  980. tbody.appendChild(tr);
  981. });
  982. }
  983. } catch (err) {
  984. console.error('Failed to load PPPoE:', err);
  985. }
  986. }
  987. function openAddPPPoEModal() {
  988. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  989. document.getElementById('pppoe-modal-edit-orig').value = '';
  990. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  991. document.getElementById('pppoe-modal-name').readOnly = false;
  992. document.getElementById('pppoe-modal-user').value = '';
  993. document.getElementById('pppoe-modal-pass').value = '';
  994. document.getElementById('pppoe-modal-service').value = '';
  995. document.getElementById('pppoe-modal-mtu').value = '1492';
  996. document.getElementById('pppoe-modal-defroute').checked = true;
  997. document.getElementById('pppoe-modal-reconnect').checked = true;
  998. document.getElementById('pppoe-modal-disabled').checked = false;
  999. // Populate profiles
  1000. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1001. // Populate interfaces
  1002. const sel = document.getElementById('pppoe-modal-iface');
  1003. sel.innerHTML = '';
  1004. (state.interfaces || []).forEach(i => {
  1005. if (i.name === 'lo') return;
  1006. const opt = document.createElement('option');
  1007. opt.value = i.name;
  1008. opt.innerText = `${i.name} (${i.role || i.type})`;
  1009. sel.appendChild(opt);
  1010. });
  1011. document.getElementById('pppoe-modal').classList.remove('hidden');
  1012. }
  1013. function openEditPPPoEModal(name) {
  1014. const inst = (state.pppoeList || []).find(i => i.name === name);
  1015. if (!inst) return;
  1016. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1017. document.getElementById('pppoe-modal-edit-orig').value = name;
  1018. document.getElementById('pppoe-modal-name').value = inst.name;
  1019. document.getElementById('pppoe-modal-name').readOnly = true;
  1020. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1021. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1022. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1023. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1024. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1025. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1026. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1027. // Populate profiles
  1028. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1029. const sel = document.getElementById('pppoe-modal-iface');
  1030. sel.innerHTML = '';
  1031. (state.interfaces || []).forEach(i => {
  1032. if (i.name === 'lo') return;
  1033. const opt = document.createElement('option');
  1034. opt.value = i.name;
  1035. opt.innerText = `${i.name} (${i.role || i.type})`;
  1036. if (i.name === inst.interface) opt.selected = true;
  1037. sel.appendChild(opt);
  1038. });
  1039. document.getElementById('pppoe-modal').classList.remove('hidden');
  1040. }
  1041. function closePPPoEModal() {
  1042. document.getElementById('pppoe-modal').classList.add('hidden');
  1043. }
  1044. async function submitSavePPPoE(e) {
  1045. e.preventDefault();
  1046. const name = document.getElementById('pppoe-modal-name').value.trim();
  1047. const iface = document.getElementById('pppoe-modal-iface').value;
  1048. const user = document.getElementById('pppoe-modal-user').value.trim();
  1049. const pass = document.getElementById('pppoe-modal-pass').value;
  1050. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1051. const service = document.getElementById('pppoe-modal-service').value.trim();
  1052. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1053. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1054. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1055. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1056. try {
  1057. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1058. method: 'POST',
  1059. headers: { 'Content-Type': 'application/json' },
  1060. body: JSON.stringify({
  1061. name,
  1062. interface: iface,
  1063. username: user,
  1064. password: pass,
  1065. profile: profile,
  1066. service_name: service,
  1067. mtu,
  1068. default_route: defRoute,
  1069. auto_reconnect: reconnect,
  1070. disabled
  1071. })
  1072. });
  1073. if (res.ok) {
  1074. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1075. closePPPoEModal();
  1076. loadPPPoE(false);
  1077. fetchData(false);
  1078. } else {
  1079. const err = await res.json();
  1080. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1081. }
  1082. } catch (err) {
  1083. showToast('Error', err.message, 'error');
  1084. }
  1085. }
  1086. async function connectPPPoEInstance(name) {
  1087. try {
  1088. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1089. if (res.ok) {
  1090. showToast('Connecting', `Dialing ${name}...`, 'info');
  1091. setTimeout(() => loadPPPoE(false), 2000);
  1092. }
  1093. } catch (err) {
  1094. showToast('Error', err.message, 'error');
  1095. }
  1096. }
  1097. async function disconnectPPPoEInstance(name) {
  1098. try {
  1099. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1100. if (res.ok) {
  1101. showToast('Disconnected', `${name} session terminated`, 'info');
  1102. setTimeout(() => loadPPPoE(false), 1000);
  1103. }
  1104. } catch (err) {
  1105. showToast('Error', err.message, 'error');
  1106. }
  1107. }
  1108. async function togglePPPoEState(name, enable) {
  1109. try {
  1110. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1111. method: 'POST',
  1112. headers: { 'Content-Type': 'application/json' },
  1113. body: JSON.stringify({ enabled: enable })
  1114. });
  1115. if (res.ok) {
  1116. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1117. loadPPPoE(false);
  1118. }
  1119. } catch (err) {
  1120. showToast('Error', err.message, 'error');
  1121. }
  1122. }
  1123. async function deletePPPoEInstance(name) {
  1124. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1125. try {
  1126. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1127. if (res.ok) {
  1128. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1129. loadPPPoE(false);
  1130. fetchData(false);
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1137. state.wgSubTab = 'ifaces';
  1138. function switchWGSubTab(tab) {
  1139. state.wgSubTab = tab;
  1140. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1141. const peersPanel = document.getElementById('wg-subtab-peers');
  1142. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1143. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1144. if (tab === 'ifaces') {
  1145. ifacesPanel?.classList.remove('hidden');
  1146. peersPanel?.classList.add('hidden');
  1147. 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';
  1148. 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';
  1149. } else {
  1150. ifacesPanel?.classList.add('hidden');
  1151. peersPanel?.classList.remove('hidden');
  1152. 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';
  1153. 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';
  1154. renderWGPeers();
  1155. }
  1156. }
  1157. async function loadWireGuard(populateInputs = true) {
  1158. try {
  1159. const [ifacesRes, peersRes] = await Promise.all([
  1160. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1161. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1162. ]);
  1163. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1164. const peers = peersRes.ok ? await peersRes.json() : [];
  1165. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1166. state.wgPeers = Array.isArray(peers) ? peers : [];
  1167. // Badges
  1168. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1169. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1170. const peersCountBadge = document.getElementById('wg-peers-count');
  1171. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1172. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1173. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1174. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1175. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1176. // Render Interfaces
  1177. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1178. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1179. if (ifacesTbody) {
  1180. ifacesTbody.innerHTML = '';
  1181. if (state.wgInterfaces.length === 0) {
  1182. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1183. } else {
  1184. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1185. state.wgInterfaces.forEach(iface => {
  1186. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1187. const tr = document.createElement('tr');
  1188. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1189. tr.innerHTML = `
  1190. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1191. <td class="py-2.5 px-3">
  1192. <div class="flex items-center gap-1.5">
  1193. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1194. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1195. </div>
  1196. </td>
  1197. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1198. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1199. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1200. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1201. ${(iface.public_key || '').substring(0, 10)}... 📋
  1202. </span>
  1203. </td>
  1204. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1205. <td class="py-2.5 px-3 text-center">
  1206. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1207. </td>
  1208. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1209. ${iface.running ? `
  1210. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1211. ` : `
  1212. <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>
  1213. `}
  1214. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1215. ${iface.disabled ? 'Enable' : 'Disable'}
  1216. </button>
  1217. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1218. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1219. </td>
  1220. `;
  1221. ifacesTbody.appendChild(tr);
  1222. });
  1223. }
  1224. }
  1225. // Populate filter dropdown in peers tab
  1226. const filterSel = document.getElementById('wg-peers-filter-iface');
  1227. if (filterSel) {
  1228. const currentVal = filterSel.value;
  1229. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1230. state.wgInterfaces.forEach(i => {
  1231. const opt = document.createElement('option');
  1232. opt.value = i.name;
  1233. opt.innerText = i.name;
  1234. if (i.name === currentVal) opt.selected = true;
  1235. filterSel.appendChild(opt);
  1236. });
  1237. }
  1238. renderWGPeers();
  1239. } catch (err) {
  1240. console.error('Failed to load WireGuard:', err);
  1241. }
  1242. }
  1243. function renderWGPeers() {
  1244. const filterSel = document.getElementById('wg-peers-filter-iface');
  1245. const selectedIface = filterSel ? filterSel.value : '';
  1246. const tbody = document.getElementById('wg-peers-table-body');
  1247. const empty = document.getElementById('wg-peers-empty');
  1248. if (!tbody) return;
  1249. tbody.innerHTML = '';
  1250. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1251. if (filtered.length === 0) {
  1252. if (empty) empty.classList.remove('hidden');
  1253. } else {
  1254. if (empty) empty.classList.add('hidden');
  1255. filtered.forEach(p => {
  1256. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1257. const tr = document.createElement('tr');
  1258. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1259. tr.innerHTML = `
  1260. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1261. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1262. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1263. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1264. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1265. ${(p.public_key || '').substring(0, 10)}... 📋
  1266. </span>
  1267. </td>
  1268. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1269. <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>
  1270. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1271. <td class="py-2.5 px-3 font-mono text-[11px]">
  1272. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1273. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1274. </td>
  1275. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1276. <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">
  1277. ${p.disabled ? 'Enable' : 'Disable'}
  1278. </button>
  1279. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1280. <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>
  1281. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1282. </td>
  1283. `;
  1284. tbody.appendChild(tr);
  1285. });
  1286. }
  1287. }
  1288. function openAddWGInterfaceModal() {
  1289. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1290. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1291. const nameEl = document.getElementById('wg-iface-modal-name');
  1292. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1293. nameEl.readOnly = false;
  1294. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1295. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1296. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1297. document.getElementById('wg-iface-modal-comment').value = '';
  1298. document.getElementById('wg-iface-modal-pubkey').value = '';
  1299. document.getElementById('wg-iface-modal-privkey').value = '';
  1300. document.getElementById('wg-iface-modal-disabled').checked = false;
  1301. generateWGInterfaceKeys();
  1302. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1303. }
  1304. function openEditWGInterfaceModal(name) {
  1305. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1306. if (!iface) return;
  1307. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1308. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1309. const nameEl = document.getElementById('wg-iface-modal-name');
  1310. nameEl.value = iface.name;
  1311. nameEl.readOnly = false; // ALLOW RENAMING
  1312. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1313. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1314. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1315. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1316. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1317. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1318. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1319. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1320. }
  1321. function closeAddWGInterfaceModal() {
  1322. document.getElementById('wg-iface-modal').classList.add('hidden');
  1323. }
  1324. async function generateWGInterfaceKeys() {
  1325. try {
  1326. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1327. const keys = await res.json();
  1328. if (res.ok) {
  1329. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1330. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1331. }
  1332. } catch (err) {
  1333. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1334. }
  1335. }
  1336. async function onWGInterfacePrivKeyInput() {
  1337. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1338. if (!privKey) return;
  1339. try {
  1340. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1341. method: 'POST',
  1342. headers: { 'Content-Type': 'application/json' },
  1343. body: JSON.stringify({ private_key: privKey })
  1344. });
  1345. if (res.ok) {
  1346. const data = await res.json();
  1347. if (data.public_key) {
  1348. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1349. }
  1350. }
  1351. } catch (err) {
  1352. // Ignore while typing
  1353. }
  1354. }
  1355. function toggleWGPrivKeyVisibility() {
  1356. const el = document.getElementById('wg-iface-modal-privkey');
  1357. const btn = document.getElementById('btn-toggle-wg-privkey');
  1358. if (el.type === 'password') {
  1359. el.type = 'text';
  1360. btn.innerText = '🙈 Hide';
  1361. } else {
  1362. el.type = 'password';
  1363. btn.innerText = '👁️ Show';
  1364. }
  1365. }
  1366. function copyWGInterfacePubKey() {
  1367. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1368. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1369. }
  1370. async function submitSaveWGInterface(e) {
  1371. e.preventDefault();
  1372. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1373. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1374. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1375. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1376. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1377. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1378. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1379. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1380. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1381. try {
  1382. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1383. method: 'POST',
  1384. headers: { 'Content-Type': 'application/json' },
  1385. body: JSON.stringify({
  1386. orig_name: origName,
  1387. name,
  1388. listen_port: port,
  1389. address: addr,
  1390. mtu,
  1391. comment,
  1392. public_key: pub,
  1393. private_key: priv,
  1394. disabled
  1395. })
  1396. });
  1397. const data = await res.json();
  1398. if (res.ok) {
  1399. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1400. closeAddWGInterfaceModal();
  1401. loadWireGuard(false);
  1402. fetchData(false);
  1403. } else {
  1404. showToast('Error', data.error || 'Failed to save interface', 'error');
  1405. }
  1406. } catch (err) {
  1407. showToast('Error', err.message, 'error');
  1408. }
  1409. }
  1410. async function startWGInterface(name) {
  1411. try {
  1412. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1413. if (res.ok) {
  1414. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1415. loadWireGuard(false);
  1416. fetchData(false);
  1417. }
  1418. } catch (err) {
  1419. showToast('Error', err.message, 'error');
  1420. }
  1421. }
  1422. async function stopWGInterface(name) {
  1423. try {
  1424. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1425. if (res.ok) {
  1426. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1427. loadWireGuard(false);
  1428. fetchData(false);
  1429. }
  1430. } catch (err) {
  1431. showToast('Error', err.message, 'error');
  1432. }
  1433. }
  1434. async function toggleWGInterfaceState(name, enable) {
  1435. try {
  1436. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1437. method: 'POST',
  1438. headers: { 'Content-Type': 'application/json' },
  1439. body: JSON.stringify({ enabled: enable })
  1440. });
  1441. if (res.ok) {
  1442. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1443. loadWireGuard(false);
  1444. fetchData(false);
  1445. }
  1446. } catch (err) {
  1447. showToast('Error', err.message, 'error');
  1448. }
  1449. }
  1450. async function deleteWGInterface(name) {
  1451. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1452. try {
  1453. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1454. if (res.ok) {
  1455. showToast('Deleted', `Interface ${name} removed`, 'success');
  1456. loadWireGuard(false);
  1457. fetchData(false);
  1458. }
  1459. } catch (err) {
  1460. showToast('Error', err.message, 'error');
  1461. }
  1462. }
  1463. function populateWGPeerIfaceSelect(selectedIface = '') {
  1464. const sel = document.getElementById('wg-peer-modal-iface');
  1465. if (!sel) return;
  1466. sel.innerHTML = '';
  1467. (state.wgInterfaces || []).forEach(i => {
  1468. const opt = document.createElement('option');
  1469. opt.value = i.name;
  1470. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1471. if (i.name === selectedIface) opt.selected = true;
  1472. sel.appendChild(opt);
  1473. });
  1474. }
  1475. function openAddWGPeerModal() {
  1476. if ((state.wgInterfaces || []).length === 0) {
  1477. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1478. openAddWGInterfaceModal();
  1479. return;
  1480. }
  1481. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1482. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1483. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1484. populateWGPeerIfaceSelect();
  1485. document.getElementById('wg-peer-modal-name').value = '';
  1486. document.getElementById('wg-peer-modal-pubkey').value = '';
  1487. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1488. document.getElementById('wg-peer-modal-endpoint').value = '';
  1489. document.getElementById('wg-peer-modal-port').value = '';
  1490. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1491. document.getElementById('wg-peer-modal-preshared').value = '';
  1492. document.getElementById('wg-peer-modal-disabled').checked = false;
  1493. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1494. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1495. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1496. }
  1497. function openEditWGPeerModal(ifaceName, pubKey) {
  1498. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1499. if (!peer) {
  1500. showToast('Not Found', 'Peer not found', 'warning');
  1501. return;
  1502. }
  1503. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1504. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1505. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1506. populateWGPeerIfaceSelect(peer.interface);
  1507. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1508. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1509. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1510. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1511. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1512. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1513. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1514. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1515. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1516. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1517. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1518. }
  1519. function closeAddWGPeerModal() {
  1520. document.getElementById('wg-peer-modal').classList.add('hidden');
  1521. }
  1522. async function generatePeerKeypairHelper() {
  1523. try {
  1524. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1525. const keys = await res.json();
  1526. if (res.ok) {
  1527. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1528. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1529. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1530. checkWGPeerKeyValidity();
  1531. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1532. }
  1533. } catch (err) {
  1534. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1535. }
  1536. }
  1537. function copyGeneratedPeerPrivKey() {
  1538. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1539. if (priv) copyToClipboard(priv, 'Client Private Key');
  1540. }
  1541. async function generatePeerPSK() {
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1544. const keys = await res.json();
  1545. if (res.ok && keys.private_key) {
  1546. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1547. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1548. }
  1549. } catch (err) {
  1550. showToast('Error', err.message, 'error');
  1551. }
  1552. }
  1553. function checkWGPeerKeyValidity() {
  1554. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1555. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1556. const warningEl = document.getElementById('wg-peer-key-warning');
  1557. if (!warningEl) return;
  1558. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1559. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1560. warningEl.classList.remove('hidden');
  1561. } else {
  1562. warningEl.classList.add('hidden');
  1563. }
  1564. }
  1565. async function submitSaveWGPeer(e) {
  1566. e.preventDefault();
  1567. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1568. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1569. const iface = document.getElementById('wg-peer-modal-iface').value;
  1570. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1571. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1572. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1573. .split(',')
  1574. .map(s => s.trim())
  1575. .filter(s => s.length > 0);
  1576. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1577. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1578. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1579. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1580. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1581. // Validation
  1582. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1583. if (targetIface && targetIface.public_key === pub) {
  1584. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1585. return;
  1586. }
  1587. try {
  1588. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1589. method: 'POST',
  1590. headers: { 'Content-Type': 'application/json' },
  1591. body: JSON.stringify({
  1592. orig_interface: origIface,
  1593. orig_public_key: origPubKey,
  1594. interface: iface,
  1595. name,
  1596. public_key: pub,
  1597. allowed_ips: allowed,
  1598. endpoint_address: epHost,
  1599. endpoint_port: epPort,
  1600. persistent_keepalive: keepalive,
  1601. preshared_key: psk,
  1602. disabled
  1603. })
  1604. });
  1605. const data = await res.json();
  1606. if (res.ok) {
  1607. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1608. closeAddWGPeerModal();
  1609. loadWireGuard(false);
  1610. } else {
  1611. showToast('Error', data.error || 'Failed to save peer', 'error');
  1612. }
  1613. } catch (err) {
  1614. showToast('Error', err.message, 'error');
  1615. }
  1616. }
  1617. async function toggleWGPeerState(iface, pubkey, enable) {
  1618. try {
  1619. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1620. method: 'POST',
  1621. headers: { 'Content-Type': 'application/json' },
  1622. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1623. });
  1624. const data = await res.json();
  1625. if (res.ok) {
  1626. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1627. loadWireGuard(false);
  1628. } else {
  1629. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1630. }
  1631. } catch (err) {
  1632. showToast('Error', err.message, 'error');
  1633. }
  1634. }
  1635. async function deleteWGPeer(iface, pubkey) {
  1636. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1637. try {
  1638. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1639. method: 'POST',
  1640. headers: { 'Content-Type': 'application/json' },
  1641. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1642. });
  1643. const data = await res.json();
  1644. if (res.ok) {
  1645. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1646. loadWireGuard(false);
  1647. } else {
  1648. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1649. }
  1650. } catch (err) {
  1651. showToast('Error', err.message, 'error');
  1652. }
  1653. }
  1654. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1655. function switchIpsecModalTab(tab) {
  1656. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1657. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1658. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1659. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1660. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1661. if (tab === 'p1') {
  1662. if (p1Tab) {
  1663. 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';
  1664. }
  1665. if (p2Tab) {
  1666. 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';
  1667. }
  1668. if (p1Content) p1Content.classList.remove('hidden');
  1669. if (p2Content) p2Content.classList.add('hidden');
  1670. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1671. } else {
  1672. if (p1Tab) {
  1673. 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';
  1674. }
  1675. if (p2Tab) {
  1676. 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';
  1677. }
  1678. if (p1Content) p1Content.classList.add('hidden');
  1679. if (p2Content) p2Content.classList.remove('hidden');
  1680. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1681. }
  1682. }
  1683. function toggleIpsecPhaseStep() {
  1684. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1685. if (p1Content && !p1Content.classList.contains('hidden')) {
  1686. switchIpsecModalTab('p2');
  1687. } else {
  1688. switchIpsecModalTab('p1');
  1689. }
  1690. }
  1691. function toggleIpsecPskVisibility() {
  1692. const pskInput = document.getElementById('ipsec-modal-psk');
  1693. if (!pskInput) return;
  1694. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1695. }
  1696. function addIpsecLocalSubnet(val = '') {
  1697. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1698. if (!container) return;
  1699. const row = document.createElement('div');
  1700. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1701. row.innerHTML = `
  1702. <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">
  1703. <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>
  1704. `;
  1705. container.appendChild(row);
  1706. }
  1707. function addIpsecRemoteSubnet(val = '') {
  1708. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1709. if (!container) return;
  1710. const row = document.createElement('div');
  1711. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1712. row.innerHTML = `
  1713. <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">
  1714. <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>
  1715. `;
  1716. container.appendChild(row);
  1717. }
  1718. function updateIpsecEspProposalFromPFS(val) {
  1719. const prop = document.getElementById('ipsec-modal-espprop');
  1720. if (!prop) return;
  1721. if (val === 'none') {
  1722. prop.value = 'aes256-sha256,aes128-sha256,default';
  1723. } else {
  1724. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1725. }
  1726. }
  1727. function updateIpsecIkeProposalFromDH(dh) {
  1728. const el = document.getElementById('ipsec-modal-ikeprop');
  1729. if (el) {
  1730. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1731. }
  1732. }
  1733. function safeSetVal(id, val) {
  1734. const el = document.getElementById(id);
  1735. if (el) el.value = val;
  1736. }
  1737. function safeSetChecked(id, val) {
  1738. const el = document.getElementById(id);
  1739. if (el) el.checked = !!val;
  1740. }
  1741. function safeGetVal(id, def = '') {
  1742. const el = document.getElementById(id);
  1743. return el ? el.value : def;
  1744. }
  1745. async function loadIPSec(populateInputs = true) {
  1746. try {
  1747. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1748. const list = await res.json();
  1749. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1750. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1751. const badge = document.getElementById('ipsec-sas-badge');
  1752. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1753. const tbody = document.getElementById('ipsec-table-body');
  1754. const empty = document.getElementById('ipsec-empty');
  1755. if (!tbody) return;
  1756. tbody.innerHTML = '';
  1757. if (state.ipsecTunnels.length === 0) {
  1758. if (empty) empty.classList.remove('hidden');
  1759. } else {
  1760. if (empty) empty.classList.add('hidden');
  1761. state.ipsecTunnels.forEach(c => {
  1762. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1763. const tr = document.createElement('tr');
  1764. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1765. // Local subnets tags
  1766. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1767. 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('');
  1768. // Remote subnets tags
  1769. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1770. 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('');
  1771. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1772. const p2Name = c.phase2_name || `${c.name}_p2`;
  1773. tr.innerHTML = `
  1774. <td class="py-2.5 px-3 text-center">
  1775. ${isEstablished ? `
  1776. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1777. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1778. <span>UP</span>
  1779. </span>
  1780. ` : (c.disabled ? `
  1781. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1782. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1783. <span>DOWN</span>
  1784. </span>
  1785. ` : `
  1786. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1787. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1788. <span>IDLE</span>
  1789. </span>
  1790. `)}
  1791. </td>
  1792. <td class="py-2.5 px-4 font-bold text-white">
  1793. <div class="flex items-center gap-2">
  1794. <span class="text-amber-400">🛡</span>
  1795. <div>
  1796. <div>${escapeHtml(c.name)}</div>
  1797. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1798. </div>
  1799. </div>
  1800. </td>
  1801. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1802. <td class="py-2.5 px-4 font-sans">
  1803. <div class="flex items-center gap-1.5">
  1804. <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>
  1805. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1806. </div>
  1807. </td>
  1808. <td class="py-2.5 px-4">
  1809. <div class="space-y-1">
  1810. <div class="flex items-center flex-wrap gap-1">
  1811. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1812. ${localBadges}
  1813. </div>
  1814. <div class="flex items-center flex-wrap gap-1">
  1815. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1816. ${remoteBadges}
  1817. </div>
  1818. </div>
  1819. </td>
  1820. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1821. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1822. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1823. </div>
  1824. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1825. </td>
  1826. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1827. ${isEstablished ? `
  1828. <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>
  1829. ` : `
  1830. <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>
  1831. `}
  1832. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1833. ${c.disabled ? 'Enable' : 'Disable'}
  1834. </button>
  1835. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1836. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1837. </td>
  1838. `;
  1839. tbody.appendChild(tr);
  1840. });
  1841. }
  1842. } catch (err) {
  1843. console.error('Failed to load IPSec:', err);
  1844. }
  1845. }
  1846. function openAddIPSecModal() {
  1847. const modal = document.getElementById('ipsec-modal');
  1848. if (!modal) return;
  1849. const title = document.getElementById('ipsec-modal-title');
  1850. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1851. // Phase 1 Fields
  1852. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1853. const nameEl = document.getElementById('ipsec-modal-name');
  1854. if (nameEl) nameEl.readOnly = false;
  1855. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1856. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1857. safeSetVal('ipsec-modal-remotegw', '');
  1858. safeSetVal('ipsec-modal-localaddrs', '');
  1859. safeSetVal('ipsec-modal-comments', '');
  1860. safeSetVal('ipsec-modal-psk', '');
  1861. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1862. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1863. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1864. safeSetVal('ipsec-modal-localid', '');
  1865. safeSetVal('ipsec-modal-remoteid', '');
  1866. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1867. // Phase 2 Fields
  1868. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1869. safeSetVal('ipsec-modal-espkeylife', '28800');
  1870. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1871. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1872. safeSetChecked('ipsec-modal-autostart', true);
  1873. safeSetChecked('ipsec-modal-disabled', false);
  1874. // Clear & Populate default dynamic subnets
  1875. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1876. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1877. if (localContainer) {
  1878. localContainer.innerHTML = '';
  1879. addIpsecLocalSubnet('192.168.10.0/24');
  1880. }
  1881. if (remoteContainer) {
  1882. remoteContainer.innerHTML = '';
  1883. addIpsecRemoteSubnet('192.168.20.0/24');
  1884. }
  1885. switchIpsecModalTab('p1');
  1886. modal.classList.remove('hidden');
  1887. }
  1888. function openEditIPSecModal(name) {
  1889. const modal = document.getElementById('ipsec-modal');
  1890. if (!modal) return;
  1891. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1892. if (!conn) return;
  1893. const title = document.getElementById('ipsec-modal-title');
  1894. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1895. // Phase 1 Fields
  1896. safeSetVal('ipsec-modal-name', conn.name);
  1897. const nameEl = document.getElementById('ipsec-modal-name');
  1898. if (nameEl) nameEl.readOnly = true;
  1899. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1900. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1901. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1902. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1903. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1904. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1905. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1906. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1907. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1908. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1909. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1910. // Phase 2 Fields
  1911. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1912. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1913. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1914. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1915. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1916. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1917. // Populate dynamic subnets
  1918. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1919. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1920. if (localContainer) {
  1921. localContainer.innerHTML = '';
  1922. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1923. locals.forEach(s => addIpsecLocalSubnet(s));
  1924. }
  1925. if (remoteContainer) {
  1926. remoteContainer.innerHTML = '';
  1927. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1928. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1929. }
  1930. switchIpsecModalTab('p1');
  1931. modal.classList.remove('hidden');
  1932. }
  1933. function closeAddIPSecModal() {
  1934. const modal = document.getElementById('ipsec-modal');
  1935. if (modal) modal.classList.add('hidden');
  1936. }
  1937. async function submitSaveIPSec(e) {
  1938. if (e) e.preventDefault();
  1939. const name = safeGetVal('ipsec-modal-name').trim();
  1940. if (!name) {
  1941. showToast('Error', 'Tunnel name is required', 'error');
  1942. return;
  1943. }
  1944. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1945. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1946. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1947. const comments = safeGetVal('ipsec-modal-comments').trim();
  1948. const psk = safeGetVal('ipsec-modal-psk');
  1949. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1950. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1951. const localId = safeGetVal('ipsec-modal-localid').trim();
  1952. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1953. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1954. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1955. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1956. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1957. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1958. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1959. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1960. // Scrape dynamic local and remote subnets
  1961. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1962. const localSubnets = [];
  1963. localInputs.forEach(inp => {
  1964. const v = inp.value.trim();
  1965. if (v) localSubnets.push(v);
  1966. });
  1967. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1968. const remoteSubnets = [];
  1969. remoteInputs.forEach(inp => {
  1970. const v = inp.value.trim();
  1971. if (v) remoteSubnets.push(v);
  1972. });
  1973. try {
  1974. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1975. method: 'POST',
  1976. headers: { 'Content-Type': 'application/json' },
  1977. body: JSON.stringify({
  1978. name,
  1979. comment: comments,
  1980. ike_version: ikeVersion,
  1981. local_addrs: localAddrs,
  1982. remote_addrs: remotegw,
  1983. preshared_key: psk,
  1984. ike_proposals: ikeProposals,
  1985. ike_keylife: ikeKeylife,
  1986. local_id: localId,
  1987. remote_id: remoteId,
  1988. dpd: dpd,
  1989. phase2_name: phase2Name,
  1990. esp_proposals: espProposals,
  1991. esp_keylife: espKeylife,
  1992. pfs_group: pfsGroup,
  1993. pfs: pfsGroup !== 'none',
  1994. local_subnets: localSubnets,
  1995. remote_subnets: remoteSubnets,
  1996. local_subnet: localSubnets[0] || '0.0.0.0/0',
  1997. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  1998. auto_start: autostart,
  1999. disabled
  2000. })
  2001. });
  2002. if (res.ok) {
  2003. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2004. closeAddIPSecModal();
  2005. loadIPSec(false);
  2006. } else {
  2007. const err = await res.json();
  2008. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2009. }
  2010. } catch (err) {
  2011. showToast('Error', err.message, 'error');
  2012. }
  2013. }
  2014. async function startIPSecTunnel(name) {
  2015. try {
  2016. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2017. if (res.ok) {
  2018. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2019. setTimeout(() => loadIPSec(false), 2000);
  2020. }
  2021. } catch (err) {
  2022. showToast('Error', err.message, 'error');
  2023. }
  2024. }
  2025. async function stopIPSecTunnel(name) {
  2026. try {
  2027. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2028. if (res.ok) {
  2029. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2030. loadIPSec(false);
  2031. }
  2032. } catch (err) {
  2033. showToast('Error', err.message, 'error');
  2034. }
  2035. }
  2036. async function toggleIPSecState(name, enable) {
  2037. try {
  2038. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2039. method: 'POST',
  2040. headers: { 'Content-Type': 'application/json' },
  2041. body: JSON.stringify({ enabled: enable })
  2042. });
  2043. if (res.ok) {
  2044. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2045. loadIPSec(false);
  2046. }
  2047. } catch (err) {
  2048. showToast('Error', err.message, 'error');
  2049. }
  2050. }
  2051. async function deleteIPSecConn(name) {
  2052. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2053. try {
  2054. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2055. if (res.ok) {
  2056. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2057. loadIPSec(false);
  2058. fetchData(false);
  2059. }
  2060. } catch (err) {
  2061. showToast('Error', err.message, 'error');
  2062. }
  2063. }
  2064. // ======================== L2TP Multi-Instance ========================
  2065. async function loadL2TP(populateInputs = true) {
  2066. try {
  2067. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2068. await fetchPPPProfilesList();
  2069. }
  2070. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2071. const list = await res.json();
  2072. state.l2tpList = Array.isArray(list) ? list : [];
  2073. const badge = document.getElementById('l2tp-count-badge');
  2074. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2075. const tbody = document.getElementById('l2tp-table-body');
  2076. const empty = document.getElementById('l2tp-empty');
  2077. if (!tbody) return;
  2078. tbody.innerHTML = '';
  2079. if (state.l2tpList.length === 0) {
  2080. if (empty) empty.classList.remove('hidden');
  2081. } else {
  2082. if (empty) empty.classList.add('hidden');
  2083. state.l2tpList.forEach(inst => {
  2084. const tr = document.createElement('tr');
  2085. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2086. tr.innerHTML = `
  2087. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2088. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2089. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2090. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2091. <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>
  2092. <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>
  2093. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2094. <td class="py-2.5 px-3 text-center">
  2095. <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'}">
  2096. ${inst.default_route ? 'Yes' : 'No'}
  2097. </span>
  2098. </td>
  2099. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2100. ${inst.running ? `
  2101. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2102. ` : `
  2103. <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>
  2104. `}
  2105. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2106. ${inst.disabled ? 'Enable' : 'Disable'}
  2107. </button>
  2108. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2109. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2110. </td>
  2111. `;
  2112. tbody.appendChild(tr);
  2113. });
  2114. }
  2115. } catch (err) {
  2116. console.error('Failed to load L2TP:', err);
  2117. }
  2118. }
  2119. function openAddL2TPModal() {
  2120. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2121. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2122. document.getElementById('l2tp-modal-name').readOnly = false;
  2123. document.getElementById('l2tp-modal-server').value = '';
  2124. document.getElementById('l2tp-modal-user').value = '';
  2125. document.getElementById('l2tp-modal-pass').value = '';
  2126. document.getElementById('l2tp-modal-ipsec').value = '';
  2127. document.getElementById('l2tp-modal-defroute').checked = true;
  2128. document.getElementById('l2tp-modal-disabled').checked = false;
  2129. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2130. document.getElementById('l2tp-modal').classList.remove('hidden');
  2131. }
  2132. function openEditL2TPModal(name) {
  2133. const inst = (state.l2tpList || []).find(i => i.name === name);
  2134. if (!inst) return;
  2135. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2136. document.getElementById('l2tp-modal-name').value = inst.name;
  2137. document.getElementById('l2tp-modal-name').readOnly = true;
  2138. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2139. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2140. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2141. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2142. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2143. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2144. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2145. document.getElementById('l2tp-modal').classList.remove('hidden');
  2146. }
  2147. function closeL2TPModal() {
  2148. document.getElementById('l2tp-modal').classList.add('hidden');
  2149. }
  2150. async function submitSaveL2TP(e) {
  2151. e.preventDefault();
  2152. const name = document.getElementById('l2tp-modal-name').value.trim();
  2153. const server = document.getElementById('l2tp-modal-server').value.trim();
  2154. const user = document.getElementById('l2tp-modal-user').value.trim();
  2155. const pass = document.getElementById('l2tp-modal-pass').value;
  2156. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2157. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2158. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2159. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2160. try {
  2161. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2162. method: 'POST',
  2163. headers: { 'Content-Type': 'application/json' },
  2164. body: JSON.stringify({
  2165. name,
  2166. connect_to: server,
  2167. username: user,
  2168. password: pass,
  2169. profile: profile,
  2170. ipsec_secret: ipsec,
  2171. default_route: defRoute,
  2172. disabled
  2173. })
  2174. });
  2175. if (res.ok) {
  2176. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2177. closeL2TPModal();
  2178. loadL2TP(false);
  2179. fetchData(false);
  2180. }
  2181. } catch (err) {
  2182. showToast('Error', err.message, 'error');
  2183. }
  2184. }
  2185. async function connectL2TPInstance(name) {
  2186. try {
  2187. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2188. if (res.ok) {
  2189. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2190. setTimeout(() => loadL2TP(false), 2000);
  2191. }
  2192. } catch (err) {
  2193. showToast('Error', err.message, 'error');
  2194. }
  2195. }
  2196. async function disconnectL2TPInstance(name) {
  2197. try {
  2198. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2199. if (res.ok) {
  2200. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2201. loadL2TP(false);
  2202. }
  2203. } catch (err) {
  2204. showToast('Error', err.message, 'error');
  2205. }
  2206. }
  2207. async function toggleL2TPState(name, enable) {
  2208. try {
  2209. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2210. method: 'POST',
  2211. headers: { 'Content-Type': 'application/json' },
  2212. body: JSON.stringify({ enabled: enable })
  2213. });
  2214. if (res.ok) {
  2215. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2216. loadL2TP(false);
  2217. }
  2218. } catch (err) {
  2219. showToast('Error', err.message, 'error');
  2220. }
  2221. }
  2222. async function deleteL2TPInstance(name) {
  2223. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2224. try {
  2225. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2226. if (res.ok) {
  2227. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2228. loadL2TP(false);
  2229. fetchData(false);
  2230. }
  2231. } catch (err) {
  2232. showToast('Error', err.message, 'error');
  2233. }
  2234. }
  2235. // ======================== PPTP Multi-Instance ========================
  2236. async function loadPPTP(populateInputs = true) {
  2237. try {
  2238. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2239. await fetchPPPProfilesList();
  2240. }
  2241. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2242. const list = await res.json();
  2243. state.pptpList = Array.isArray(list) ? list : [];
  2244. const badge = document.getElementById('pptp-count-badge');
  2245. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2246. const tbody = document.getElementById('pptp-table-body');
  2247. const empty = document.getElementById('pptp-empty');
  2248. if (!tbody) return;
  2249. tbody.innerHTML = '';
  2250. if (state.pptpList.length === 0) {
  2251. if (empty) empty.classList.remove('hidden');
  2252. } else {
  2253. if (empty) empty.classList.add('hidden');
  2254. state.pptpList.forEach(inst => {
  2255. const tr = document.createElement('tr');
  2256. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2257. tr.innerHTML = `
  2258. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2259. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2260. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2261. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2262. <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>
  2263. <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>
  2264. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2265. <td class="py-2.5 px-3 text-center">
  2266. <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'}">
  2267. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2268. </span>
  2269. </td>
  2270. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2271. ${inst.running ? `
  2272. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2273. ` : `
  2274. <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>
  2275. `}
  2276. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2277. ${inst.disabled ? 'Enable' : 'Disable'}
  2278. </button>
  2279. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2280. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2281. </td>
  2282. `;
  2283. tbody.appendChild(tr);
  2284. });
  2285. }
  2286. } catch (err) {
  2287. console.error('Failed to load PPTP:', err);
  2288. }
  2289. }
  2290. function openAddPPTPModal() {
  2291. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2292. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2293. document.getElementById('pptp-modal-name').readOnly = false;
  2294. document.getElementById('pptp-modal-server').value = '';
  2295. document.getElementById('pptp-modal-user').value = '';
  2296. document.getElementById('pptp-modal-pass').value = '';
  2297. document.getElementById('pptp-modal-mppe').checked = true;
  2298. document.getElementById('pptp-modal-defroute').checked = true;
  2299. document.getElementById('pptp-modal-disabled').checked = false;
  2300. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2301. document.getElementById('pptp-modal').classList.remove('hidden');
  2302. }
  2303. function openEditPPTPModal(name) {
  2304. const inst = (state.pptpList || []).find(i => i.name === name);
  2305. if (!inst) return;
  2306. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2307. document.getElementById('pptp-modal-name').value = inst.name;
  2308. document.getElementById('pptp-modal-name').readOnly = true;
  2309. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2310. document.getElementById('pptp-modal-user').value = inst.username || '';
  2311. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2312. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2313. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2314. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2315. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2316. document.getElementById('pptp-modal').classList.remove('hidden');
  2317. }
  2318. function closePPTPModal() {
  2319. document.getElementById('pptp-modal').classList.add('hidden');
  2320. }
  2321. async function submitSavePPTP(e) {
  2322. e.preventDefault();
  2323. const name = document.getElementById('pptp-modal-name').value.trim();
  2324. const server = document.getElementById('pptp-modal-server').value.trim();
  2325. const user = document.getElementById('pptp-modal-user').value.trim();
  2326. const pass = document.getElementById('pptp-modal-pass').value;
  2327. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2328. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2329. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2330. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2331. try {
  2332. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2333. method: 'POST',
  2334. headers: { 'Content-Type': 'application/json' },
  2335. body: JSON.stringify({
  2336. name,
  2337. connect_to: server,
  2338. username: user,
  2339. password: pass,
  2340. profile: profile,
  2341. require_mppe: mppe,
  2342. default_route: defRoute,
  2343. auto_reconnect: true,
  2344. disabled
  2345. })
  2346. });
  2347. if (res.ok) {
  2348. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2349. closePPTPModal();
  2350. loadPPTP(false);
  2351. fetchData(false);
  2352. }
  2353. } catch (err) {
  2354. showToast('Error', err.message, 'error');
  2355. }
  2356. }
  2357. async function connectPPTPInstance(name) {
  2358. try {
  2359. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2360. if (res.ok) {
  2361. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2362. setTimeout(() => loadPPTP(false), 2000);
  2363. }
  2364. } catch (err) {
  2365. showToast('Error', err.message, 'error');
  2366. }
  2367. }
  2368. async function disconnectPPTPInstance(name) {
  2369. try {
  2370. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2371. if (res.ok) {
  2372. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2373. loadPPTP(false);
  2374. }
  2375. } catch (err) {
  2376. showToast('Error', err.message, 'error');
  2377. }
  2378. }
  2379. async function togglePPTPState(name, enable) {
  2380. try {
  2381. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2382. method: 'POST',
  2383. headers: { 'Content-Type': 'application/json' },
  2384. body: JSON.stringify({ enabled: enable })
  2385. });
  2386. if (res.ok) {
  2387. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2388. loadPPTP(false);
  2389. }
  2390. } catch (err) {
  2391. showToast('Error', err.message, 'error');
  2392. }
  2393. }
  2394. async function deletePPTPInstance(name) {
  2395. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2396. try {
  2397. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2398. if (res.ok) {
  2399. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2400. loadPPTP(false);
  2401. fetchData(false);
  2402. }
  2403. } catch (err) {
  2404. showToast('Error', err.message, 'error');
  2405. }
  2406. }
  2407. // ---------------- Modal & Helper Functions ----------------
  2408. function openVlanModal(defaultParent = '') {
  2409. const select = document.getElementById('vlan-parent');
  2410. select.innerHTML = '';
  2411. const allIfaces = state.interfaces || [];
  2412. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2413. if (eligible.length === 0) {
  2414. const opt = document.createElement('option');
  2415. opt.value = '';
  2416. opt.innerText = 'No VLAN-capable interfaces available';
  2417. select.appendChild(opt);
  2418. } else {
  2419. eligible.forEach(i => {
  2420. const opt = document.createElement('option');
  2421. opt.value = i.name;
  2422. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2423. if (i.name === defaultParent) opt.selected = true;
  2424. select.appendChild(opt);
  2425. });
  2426. }
  2427. document.getElementById('vlan-id').value = '';
  2428. document.getElementById('vlan-name').value = '';
  2429. document.getElementById('vlan-ip').value = '';
  2430. document.getElementById('vlan-desc').value = '';
  2431. autoSuggestVlanName();
  2432. document.getElementById('vlan-modal').classList.remove('hidden');
  2433. }
  2434. function closeVlanModal() {
  2435. document.getElementById('vlan-modal').classList.add('hidden');
  2436. }
  2437. function autoSuggestVlanName() {
  2438. const parent = document.getElementById('vlan-parent').value;
  2439. if (!parent) return;
  2440. const id = document.getElementById('vlan-id').value;
  2441. const nameInput = document.getElementById('vlan-name');
  2442. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2443. }
  2444. function setSubnetPreset(cidr) {
  2445. const ipInput = document.getElementById('vlan-ip');
  2446. const id = document.getElementById('vlan-id').value || '10';
  2447. ipInput.value = `192.168.${id}.1${cidr}`;
  2448. }
  2449. async function submitCreateVlan(e) {
  2450. e.preventDefault();
  2451. const btn = document.getElementById('vlan-submit-btn');
  2452. btn.disabled = true;
  2453. btn.innerText = 'Creating...';
  2454. const parent = document.getElementById('vlan-parent').value;
  2455. if (!parent) {
  2456. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2457. btn.disabled = false;
  2458. btn.innerText = 'Create VLAN';
  2459. return;
  2460. }
  2461. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2462. const name = document.getElementById('vlan-name').value.trim();
  2463. const ip = document.getElementById('vlan-ip').value.trim();
  2464. const role = document.getElementById('vlan-role').value;
  2465. const desc = document.getElementById('vlan-desc').value.trim();
  2466. try {
  2467. const res = await fetch(`${API_BASE}/vlans`, {
  2468. method: 'POST',
  2469. headers: { 'Content-Type': 'application/json' },
  2470. body: JSON.stringify({
  2471. parent_name: parent,
  2472. vlan_id: id,
  2473. name: name,
  2474. ip_address: ip,
  2475. role: role,
  2476. description: desc,
  2477. mtu: 1500,
  2478. auto_up: true
  2479. })
  2480. });
  2481. const data = await res.json();
  2482. if (res.ok) {
  2483. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2484. state.expandedParents.add(parent);
  2485. closeVlanModal();
  2486. await fetchData(true);
  2487. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2488. } else {
  2489. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2490. }
  2491. } catch (err) {
  2492. showToast('Error', err.message, 'error');
  2493. } finally {
  2494. btn.disabled = false;
  2495. btn.innerText = 'Create VLAN';
  2496. }
  2497. }
  2498. async function confirmDeleteVlan(name) {
  2499. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2500. try {
  2501. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2502. if (res.ok) {
  2503. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2504. closeIfaceModal();
  2505. fetchData(true);
  2506. }
  2507. } catch (err) {
  2508. showToast('Error', err.message, 'error');
  2509. }
  2510. }
  2511. function openIfaceModal(name) {
  2512. const iface = (state.interfaces || []).find(i => i.name === name);
  2513. if (!iface) return;
  2514. state.currentModalIface = iface.name;
  2515. document.getElementById('modal-iface-name').innerText = iface.name;
  2516. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2517. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2518. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2519. document.getElementById('modal-iface-desc').value = iface.description || '';
  2520. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2521. if (iface.is_vlan) {
  2522. delBtn.classList.remove('hidden');
  2523. } else {
  2524. delBtn.classList.add('hidden');
  2525. }
  2526. renderModalIPs(iface);
  2527. document.getElementById('iface-modal').classList.remove('hidden');
  2528. }
  2529. function renderModalIPs(iface) {
  2530. const container = document.getElementById('modal-ip-list');
  2531. container.innerHTML = '';
  2532. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2533. if (addrs.length === 0) {
  2534. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2535. return;
  2536. }
  2537. addrs.forEach(addr => {
  2538. const row = document.createElement('div');
  2539. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2540. row.innerHTML = `
  2541. <span class="text-white">${addr}</span>
  2542. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2543. `;
  2544. container.appendChild(row);
  2545. });
  2546. }
  2547. function closeIfaceModal() {
  2548. document.getElementById('iface-modal').classList.add('hidden');
  2549. state.currentModalIface = null;
  2550. }
  2551. async function setIfaceState(name, newState) {
  2552. await toggleInterfaceState(name, newState);
  2553. const updated = (state.interfaces || []).find(i => i.name === name);
  2554. if (updated) openIfaceModal(name);
  2555. }
  2556. async function applyMTU() {
  2557. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2558. try {
  2559. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2560. method: 'POST',
  2561. headers: { 'Content-Type': 'application/json' },
  2562. body: JSON.stringify({ mtu })
  2563. });
  2564. if (res.ok) {
  2565. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2566. fetchData(false);
  2567. }
  2568. } catch (err) {
  2569. showToast('Error', err.message, 'error');
  2570. }
  2571. }
  2572. async function addInterfaceIP() {
  2573. const ip = document.getElementById('modal-new-ip').value.trim();
  2574. if (!ip) return;
  2575. try {
  2576. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2577. method: 'POST',
  2578. headers: { 'Content-Type': 'application/json' },
  2579. body: JSON.stringify({ ip })
  2580. });
  2581. if (res.ok) {
  2582. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2583. document.getElementById('modal-new-ip').value = '';
  2584. await fetchData(false);
  2585. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2586. if (iface) renderModalIPs(iface);
  2587. } else {
  2588. const err = await res.json();
  2589. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2590. }
  2591. } catch (err) {
  2592. showToast('Error', err.message, 'error');
  2593. }
  2594. }
  2595. async function removeInterfaceIP(ip) {
  2596. if (!confirm(`Remove IP ${ip}?`)) return;
  2597. try {
  2598. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2599. method: 'DELETE',
  2600. headers: { 'Content-Type': 'application/json' },
  2601. body: JSON.stringify({ ip })
  2602. });
  2603. if (res.ok) {
  2604. showToast('IP Removed', `Removed ${ip}`, 'success');
  2605. await fetchData(false);
  2606. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2607. if (iface) renderModalIPs(iface);
  2608. }
  2609. } catch (err) {
  2610. showToast('Error', err.message, 'error');
  2611. }
  2612. }
  2613. async function saveInterfaceMetadata() {
  2614. const role = document.getElementById('modal-iface-role').value;
  2615. const desc = document.getElementById('modal-iface-desc').value.trim();
  2616. try {
  2617. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2618. method: 'POST',
  2619. headers: { 'Content-Type': 'application/json' },
  2620. body: JSON.stringify({ role, description: desc })
  2621. });
  2622. if (res.ok) {
  2623. showToast('Saved', 'Metadata updated', 'success');
  2624. closeIfaceModal();
  2625. fetchData(false);
  2626. }
  2627. } catch (err) {
  2628. showToast('Error', err.message, 'error');
  2629. }
  2630. }
  2631. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2632. state.fwSubTab = 'filter';
  2633. state.routesSubTab = 'routes';
  2634. function renderRuleFlag(disabled, hasComment) {
  2635. let flags = '';
  2636. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2637. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2638. return flags || '<span class="text-slate-600">-</span>';
  2639. }
  2640. function renderActionBadge(action) {
  2641. const act = (action || '').toLowerCase();
  2642. let color = 'bg-slate-800 text-slate-300';
  2643. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2644. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2645. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2646. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2647. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2648. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2649. }
  2650. function switchFWSubTab(tab) {
  2651. state.fwSubTab = tab;
  2652. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2653. tabs.forEach(t => {
  2654. const panel = document.getElementById(`fw-subtab-${t}`);
  2655. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2656. if (panel) {
  2657. if (t === tab) panel.classList.remove('hidden');
  2658. else panel.classList.add('hidden');
  2659. }
  2660. if (btn) {
  2661. if (t === tab) {
  2662. 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';
  2663. } else {
  2664. 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';
  2665. }
  2666. }
  2667. });
  2668. const addBtn = document.getElementById('fw-primary-add-btn');
  2669. if (addBtn) {
  2670. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2671. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2672. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2673. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2674. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2675. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2676. }
  2677. if (tab === 'geo') loadGeoIP();
  2678. if (tab === 'connections') loadConnections();
  2679. setTimeout(initTableSorting, 50);
  2680. }
  2681. function openCurrentFWModal() {
  2682. if (state.fwSubTab === 'filter') openAddFilterModal();
  2683. else if (state.fwSubTab === 'nat') openAddNATModal();
  2684. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2685. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2686. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2687. else if (state.fwSubTab === 'connections') loadConnections();
  2688. }
  2689. async function loadFirewall(populateDropdowns = true) {
  2690. try {
  2691. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2692. fetch(`${API_BASE}/firewall/summary`),
  2693. fetch(`${API_BASE}/firewall/filter`),
  2694. fetch(`${API_BASE}/firewall/nat`),
  2695. fetch(`${API_BASE}/firewall/mangle`),
  2696. fetch(`${API_BASE}/firewall/address-lists`),
  2697. fetch(`${API_BASE}/firewall/geoip/status`),
  2698. fetch(`${API_BASE}/firewall/geoip/countries`)
  2699. ]);
  2700. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2701. if (filterRes.ok) state.filterRules = await filterRes.json();
  2702. if (natRes.ok) state.natRules = await natRes.json();
  2703. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2704. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2705. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2706. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2707. // Badges
  2708. const bFilter = document.getElementById('fw-badge-filter');
  2709. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2710. const bNat = document.getElementById('fw-badge-nat');
  2711. if (bNat) bNat.innerText = (state.natRules || []).length;
  2712. const bMangle = document.getElementById('fw-badge-mangle');
  2713. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2714. const bAddr = document.getElementById('fw-badge-addrlist');
  2715. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2716. const bGeo = document.getElementById('fw-badge-geo');
  2717. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2718. renderFilterRules();
  2719. renderNATRules();
  2720. renderMangleRules();
  2721. renderAddressLists();
  2722. renderGeoCountries();
  2723. if (state.fwSubTab === 'connections') {
  2724. loadConnections();
  2725. }
  2726. } catch (err) {
  2727. console.error('Failed to load firewall:', err);
  2728. }
  2729. }
  2730. // ----------------- Filter Rules -----------------
  2731. function renderFilterRules() {
  2732. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2733. const tbody = document.getElementById('filter-table-body');
  2734. const empty = document.getElementById('filter-empty');
  2735. if (!tbody) return;
  2736. tbody.innerHTML = '';
  2737. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2738. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2739. if (rules.length === 0) {
  2740. empty?.classList.remove('hidden');
  2741. return;
  2742. }
  2743. empty?.classList.add('hidden');
  2744. rules.forEach((r, idx) => {
  2745. const tr = document.createElement('tr');
  2746. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2747. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2748. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2749. let actionExtra = '';
  2750. if (r.action === 'reject') {
  2751. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2752. } else if (r.action === 'jump') {
  2753. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2754. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2755. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2756. } else if (r.action === 'log' && r.log_prefix) {
  2757. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2758. }
  2759. tr.innerHTML = `
  2760. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2761. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2762. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2763. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2764. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2765. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2766. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2767. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2768. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2769. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2770. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2771. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2772. </td>
  2773. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2774. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2775. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2776. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2777. <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>
  2778. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2779. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2780. </td>
  2781. `;
  2782. tbody.appendChild(tr);
  2783. });
  2784. }
  2785. function formatTarget(addr, list, geo) {
  2786. const parts = [];
  2787. if (addr) parts.push(`<span>${addr}</span>`);
  2788. if (list) {
  2789. const inv = list.startsWith('!') ? '!' : '';
  2790. const clean = list.replace(/^!/, '');
  2791. 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>`);
  2792. }
  2793. if (geo) {
  2794. const inv = geo.startsWith('!') ? '!' : '';
  2795. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2796. 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>`);
  2797. }
  2798. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2799. return parts.join(' ');
  2800. }
  2801. function populateInterfaceSelect(selectId, currentVal = '') {
  2802. const sel = document.getElementById(selectId);
  2803. if (!sel) return;
  2804. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2805. (state.interfaces || []).forEach(i => {
  2806. const opt = document.createElement('option');
  2807. opt.value = i.name;
  2808. opt.innerText = `${i.name} (${i.role || i.type})`;
  2809. if (i.name === currentVal) opt.selected = true;
  2810. sel.appendChild(opt);
  2811. });
  2812. }
  2813. function populateAddressListSelect(selectId, currentVal = '') {
  2814. const sel = document.getElementById(selectId);
  2815. if (!sel) return;
  2816. sel.innerHTML = '<option value="">(None)</option>';
  2817. const cleanVal = (currentVal || '').replace(/^!/, '');
  2818. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2819. customNames.forEach(name => {
  2820. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2821. const opt = document.createElement('option');
  2822. opt.value = name;
  2823. opt.innerText = `${name} (${count} entries)`;
  2824. if (name === cleanVal) opt.selected = true;
  2825. sel.appendChild(opt);
  2826. });
  2827. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2828. const opt = document.createElement('option');
  2829. opt.value = cleanVal;
  2830. opt.innerText = cleanVal;
  2831. opt.selected = true;
  2832. sel.appendChild(opt);
  2833. }
  2834. populateCommonAddrListDatalist();
  2835. }
  2836. function populateCommonAddrListDatalist() {
  2837. const dl = document.getElementById('fw-addrlist-datalist');
  2838. if (!dl) return;
  2839. dl.innerHTML = '';
  2840. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2841. names.forEach(name => {
  2842. const opt = document.createElement('option');
  2843. opt.value = name;
  2844. dl.appendChild(opt);
  2845. });
  2846. }
  2847. function populateGeoIPSelect(selectId, currentVal = '') {
  2848. const sel = document.getElementById(selectId);
  2849. if (!sel) return;
  2850. sel.innerHTML = '<option value="">(None)</option>';
  2851. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2852. // Presets optgroup
  2853. const grpPresets = document.createElement('optgroup');
  2854. grpPresets.label = '⚡ Regional Presets';
  2855. const presets = [
  2856. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2857. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2858. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2859. ];
  2860. presets.forEach(p => {
  2861. const opt = document.createElement('option');
  2862. opt.value = p.code;
  2863. opt.innerText = p.label;
  2864. if (p.code === cleanVal) opt.selected = true;
  2865. grpPresets.appendChild(opt);
  2866. });
  2867. sel.appendChild(grpPresets);
  2868. // All Countries optgroup
  2869. const grpCountries = document.createElement('optgroup');
  2870. grpCountries.label = '🌍 All Countries';
  2871. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2872. countries.forEach(c => {
  2873. const opt = document.createElement('option');
  2874. opt.value = c.code;
  2875. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2876. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2877. if (c.code === cleanVal) opt.selected = true;
  2878. grpCountries.appendChild(opt);
  2879. });
  2880. sel.appendChild(grpCountries);
  2881. }
  2882. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2883. function switchFwRuleTab(tab) {
  2884. state.activeFwRuleTab = tab;
  2885. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2886. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2887. btn.classList.add('text-slate-400', 'border-transparent');
  2888. });
  2889. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2890. if (activeBtn) {
  2891. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2892. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2893. }
  2894. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2895. const activePane = document.getElementById(`fw-pane-${tab}`);
  2896. if (activePane) activePane.classList.remove('hidden');
  2897. if (tab === 'statistics') {
  2898. startFwStatPolling();
  2899. } else {
  2900. stopFwStatPolling();
  2901. }
  2902. }
  2903. function toggleFwField(fieldKey, expand) {
  2904. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2905. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2906. if (!plusBtn || !fieldBox) return;
  2907. if (expand) {
  2908. plusBtn.classList.add('hidden');
  2909. fieldBox.classList.remove('hidden');
  2910. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2911. if (valInput) valInput.focus();
  2912. } else {
  2913. fieldBox.classList.add('hidden');
  2914. plusBtn.classList.remove('hidden');
  2915. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2916. if (valInput) {
  2917. if (valInput.tagName === 'SELECT') {
  2918. valInput.selectedIndex = 0;
  2919. } else {
  2920. valInput.value = '';
  2921. }
  2922. }
  2923. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2924. if (invInput) invInput.checked = false;
  2925. if (fieldKey === 'cs') {
  2926. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2927. const el = document.getElementById(id);
  2928. if (el) el.checked = false;
  2929. });
  2930. }
  2931. if (fieldKey === 'natstate') {
  2932. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2933. const el = document.getElementById(id);
  2934. if (el) el.checked = false;
  2935. });
  2936. }
  2937. if (fieldKey === 'days') {
  2938. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2939. const el = document.getElementById(`fw-day-${d}`);
  2940. if (el) el.checked = true;
  2941. });
  2942. }
  2943. }
  2944. }
  2945. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2946. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2947. toggleFwField(fieldKey, true);
  2948. let strVal = String(value);
  2949. if (hasInvert) {
  2950. const inv = strVal.startsWith('!');
  2951. if (inv) strVal = strVal.slice(1);
  2952. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2953. if (invEl) invEl.checked = inv;
  2954. }
  2955. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2956. if (valEl) valEl.value = strVal;
  2957. } else {
  2958. toggleFwField(fieldKey, false);
  2959. }
  2960. }
  2961. function getFwFieldVal(fieldKey, hasInvert = false) {
  2962. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2963. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2964. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2965. let v = valEl ? valEl.value.trim() : '';
  2966. if (!v) return '';
  2967. if (hasInvert) {
  2968. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2969. if (invEl && invEl.checked) {
  2970. v = '!' + v.replace(/^!/, '');
  2971. }
  2972. }
  2973. return v;
  2974. }
  2975. function toggleMaximizeFilterModal() {
  2976. const win = document.getElementById('filter-modal-window');
  2977. if (!win) return;
  2978. if (win.classList.contains('max-w-[720px]')) {
  2979. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2980. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2981. } else {
  2982. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2983. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2984. }
  2985. }
  2986. function openAddFilterModal() {
  2987. switchFwRuleTab('general');
  2988. const badge = document.getElementById('fw-modal-badge');
  2989. if (badge) badge.innerText = 'New...';
  2990. document.getElementById('filter-modal-id').value = '';
  2991. document.getElementById('filter-modal-enabled').checked = true;
  2992. document.getElementById('filter-modal-comment').value = '';
  2993. document.getElementById('filter-modal-chain').value = 'forward';
  2994. document.getElementById('filter-modal-action').value = 'accept';
  2995. document.getElementById('filter-modal-log').checked = false;
  2996. populateInterfaceSelect('fw-val-iniface');
  2997. populateInterfaceSelect('fw-val-outiface');
  2998. populateAddressListSelect('fw-val-srclist');
  2999. populateAddressListSelect('fw-val-dstlist');
  3000. populateGeoIPSelect('fw-val-srcgeo');
  3001. populateGeoIPSelect('fw-val-dstgeo');
  3002. const allFieldKeys = [
  3003. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3004. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3005. 'routingmark', 'conntype', 'cs', 'natstate',
  3006. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3007. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3008. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3009. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3010. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3011. ];
  3012. allFieldKeys.forEach(k => toggleFwField(k, false));
  3013. resetCurrentRuleCounters();
  3014. toggleFilterActionFields();
  3015. document.getElementById('filter-modal').classList.remove('hidden');
  3016. }
  3017. function openEditFilterModal(id) {
  3018. const r = (state.filterRules || []).find(rule => rule.id === id);
  3019. if (!r) return;
  3020. switchFwRuleTab('general');
  3021. const badge = document.getElementById('fw-modal-badge');
  3022. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3023. document.getElementById('filter-modal-id').value = r.id;
  3024. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3025. document.getElementById('filter-modal-comment').value = r.comment || '';
  3026. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3027. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3028. document.getElementById('filter-modal-log').checked = !!r.log;
  3029. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3030. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3031. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3032. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3033. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3034. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3035. setFwFieldVal('src', r.src_address, true);
  3036. setFwFieldVal('dst', r.dst_address, true);
  3037. setFwFieldVal('srclist', r.src_address_list, true);
  3038. setFwFieldVal('dstlist', r.dst_address_list, true);
  3039. setFwFieldVal('srcgeo', r.src_geoip, true);
  3040. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3041. if (r.protocol && r.protocol !== 'all') {
  3042. setFwFieldVal('proto', r.protocol, true);
  3043. } else {
  3044. toggleFwField('proto', false);
  3045. }
  3046. setFwFieldVal('sport', r.src_port, true);
  3047. setFwFieldVal('dport', r.dst_port, true);
  3048. setFwFieldVal('anyport', r.any_port, true);
  3049. setFwFieldVal('iniface', r.in_interface, true);
  3050. setFwFieldVal('outiface', r.out_interface, true);
  3051. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3052. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3053. setFwFieldVal('pktmark', r.packet_mark, true);
  3054. setFwFieldVal('connmark', r.connection_mark, true);
  3055. setFwFieldVal('routingmark', r.routing_mark, true);
  3056. setFwFieldVal('conntype', r.connection_type, false);
  3057. const states = r.connection_state || [];
  3058. if (states.length > 0) {
  3059. toggleFwField('cs', true);
  3060. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3061. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3062. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3063. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3064. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3065. } else {
  3066. toggleFwField('cs', false);
  3067. }
  3068. const natStates = r.connection_nat_state || [];
  3069. if (natStates.length > 0) {
  3070. toggleFwField('natstate', true);
  3071. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3072. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3073. } else {
  3074. toggleFwField('natstate', false);
  3075. }
  3076. // Advanced tab fields
  3077. setFwFieldVal('layer7', r.layer7_protocol, false);
  3078. setFwFieldVal('content', r.content, false);
  3079. setFwFieldVal('connbytes', r.connection_bytes, false);
  3080. setFwFieldVal('connrate', r.connection_rate, false);
  3081. setFwFieldVal('pcc', r.pcc, false);
  3082. setFwFieldVal('srcmac', r.src_mac_address, true);
  3083. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3084. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3085. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3086. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3087. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3088. setFwFieldVal('tlshost', r.tls_host, false);
  3089. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3090. setFwFieldVal('priority', r.priority, false);
  3091. setFwFieldVal('dscp', r.dscp, false);
  3092. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3093. if (r.tos) {
  3094. const tosEl = document.getElementById('fw-val-tos');
  3095. if (tosEl) tosEl.value = r.tos;
  3096. }
  3097. setFwFieldVal('pktsize', r.packet_size, false);
  3098. setFwFieldVal('random', r.random, false);
  3099. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3100. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3101. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3102. setFwFieldVal('ttl', r.ttl, false);
  3103. // Extra tab fields
  3104. setFwFieldVal('time', r.time, false);
  3105. if (r.days) {
  3106. toggleFwField('days', true);
  3107. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3108. const chk = document.getElementById(`fw-day-${d}`);
  3109. if (chk) chk.checked = r.days.includes(d);
  3110. });
  3111. } else {
  3112. toggleFwField('days', false);
  3113. }
  3114. setFwFieldVal('limit', r.limit, false);
  3115. setFwFieldVal('dstlimit', r.dst_limit, false);
  3116. setFwFieldVal('psd', r.psd, false);
  3117. // Action fields
  3118. if (r.reject_with) {
  3119. const rwEl = document.getElementById('filter-modal-rejectwith');
  3120. if (rwEl) rwEl.value = r.reject_with;
  3121. }
  3122. if (r.jump_target) {
  3123. const jtEl = document.getElementById('filter-modal-jumptarget');
  3124. if (jtEl) jtEl.value = r.jump_target;
  3125. }
  3126. if (r.address_list) {
  3127. const alEl = document.getElementById('filter-modal-action-addrlist');
  3128. if (alEl) alEl.value = r.address_list;
  3129. }
  3130. if (r.address_list_timeout) {
  3131. const toEl = document.getElementById('filter-modal-action-timeout');
  3132. if (toEl) toEl.value = r.address_list_timeout;
  3133. }
  3134. setFwFieldVal('logprefix', r.log_prefix, false);
  3135. // Statistics
  3136. const bEl = document.getElementById('fw-stat-bytes');
  3137. const pEl = document.getElementById('fw-stat-packets');
  3138. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3139. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3140. state.fwLastBytes = r.bytes || 0;
  3141. state.fwLastPackets = r.packets || 0;
  3142. state.fwLastTimestamp = Date.now();
  3143. state.fwStatRateHistory = new Array(30).fill(0);
  3144. state.fwStatPktHistory = new Array(30).fill(0);
  3145. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3146. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3147. toggleFilterActionFields();
  3148. document.getElementById('filter-modal').classList.remove('hidden');
  3149. }
  3150. function closeFilterModal() {
  3151. stopFwStatPolling();
  3152. document.getElementById('filter-modal').classList.add('hidden');
  3153. }
  3154. function toggleFilterActionFields() {
  3155. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3156. const rejectBox = document.getElementById('filter-action-reject-box');
  3157. const jumpBox = document.getElementById('filter-action-jump-box');
  3158. const addrBox = document.getElementById('filter-action-addrlist-box');
  3159. if (rejectBox) {
  3160. if (act === 'reject') rejectBox.classList.remove('hidden');
  3161. else rejectBox.classList.add('hidden');
  3162. }
  3163. if (jumpBox) {
  3164. if (act === 'jump') jumpBox.classList.remove('hidden');
  3165. else jumpBox.classList.add('hidden');
  3166. }
  3167. if (addrBox) {
  3168. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3169. addrBox.classList.remove('hidden');
  3170. } else {
  3171. addrBox.classList.add('hidden');
  3172. }
  3173. }
  3174. if (act === 'log') {
  3175. const logEl = document.getElementById('filter-modal-log');
  3176. if (logEl) logEl.checked = true;
  3177. toggleFwField('logprefix', true);
  3178. }
  3179. }
  3180. function toggleFwLogPrefix() {
  3181. const isLog = document.getElementById('filter-modal-log')?.checked;
  3182. toggleFwField('logprefix', !!isLog);
  3183. }
  3184. function copyFilterRule() {
  3185. document.getElementById('filter-modal-id').value = '';
  3186. const badge = document.getElementById('fw-modal-badge');
  3187. if (badge) badge.innerText = 'New...';
  3188. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3189. }
  3190. function resetCurrentRuleCounters() {
  3191. state.fwStatRateHistory = new Array(30).fill(0);
  3192. state.fwStatPktHistory = new Array(30).fill(0);
  3193. state.fwLastBytes = 0;
  3194. state.fwLastPackets = 0;
  3195. state.fwLastTimestamp = Date.now();
  3196. const bEl = document.getElementById('fw-stat-bytes');
  3197. const pEl = document.getElementById('fw-stat-packets');
  3198. const rEl = document.getElementById('fw-stat-rate');
  3199. const prEl = document.getElementById('fw-stat-pktrate');
  3200. if (bEl) bEl.value = '0 B';
  3201. if (pEl) pEl.value = '0';
  3202. if (rEl) rEl.value = '0 bps';
  3203. if (prEl) prEl.value = '0 p/s';
  3204. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3205. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3206. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3207. }
  3208. async function resetAllFwCounters() {
  3209. try {
  3210. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3211. if (res.ok) {
  3212. resetCurrentRuleCounters();
  3213. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3214. loadFirewall(false);
  3215. }
  3216. } catch (err) {
  3217. showToast('Error', err.message, 'error');
  3218. }
  3219. }
  3220. async function applyFilterRule(closeAfter = false) {
  3221. const id = document.getElementById('filter-modal-id').value;
  3222. const chain = document.getElementById('filter-modal-chain').value;
  3223. const action = document.getElementById('filter-modal-action').value;
  3224. const comment = document.getElementById('filter-modal-comment').value.trim();
  3225. const enabled = document.getElementById('filter-modal-enabled').checked;
  3226. const src = getFwFieldVal('src', true);
  3227. const dst = getFwFieldVal('dst', true);
  3228. const srclist = getFwFieldVal('srclist', true);
  3229. const dstlist = getFwFieldVal('dstlist', true);
  3230. const srcgeo = getFwFieldVal('srcgeo', true);
  3231. const dstgeo = getFwFieldVal('dstgeo', true);
  3232. const proto = getFwFieldVal('proto', true);
  3233. const sport = getFwFieldVal('sport', true);
  3234. const dport = getFwFieldVal('dport', true);
  3235. const anyport = getFwFieldVal('anyport', true);
  3236. const iniface = getFwFieldVal('iniface', true);
  3237. const outiface = getFwFieldVal('outiface', true);
  3238. const inifacelist = getFwFieldVal('inifacelist', true);
  3239. const outifacelist = getFwFieldVal('outifacelist', true);
  3240. const pktmark = getFwFieldVal('pktmark', true);
  3241. const connmark = getFwFieldVal('connmark', true);
  3242. const routingmark = getFwFieldVal('routingmark', true);
  3243. const conntype = getFwFieldVal('conntype', false);
  3244. const states = [];
  3245. const csBox = document.getElementById('fw-field-cs');
  3246. if (csBox && !csBox.classList.contains('hidden')) {
  3247. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3248. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3249. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3250. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3251. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3252. }
  3253. const natStates = [];
  3254. const natBox = document.getElementById('fw-field-natstate');
  3255. if (natBox && !natBox.classList.contains('hidden')) {
  3256. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3257. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3258. }
  3259. const payload = {
  3260. id,
  3261. chain,
  3262. action,
  3263. protocol: proto || 'all',
  3264. src_address: src,
  3265. dst_address: dst,
  3266. src_port: sport,
  3267. dst_port: dport,
  3268. any_port: anyport,
  3269. in_interface: iniface,
  3270. out_interface: outiface,
  3271. in_interface_list: inifacelist,
  3272. out_interface_list: outifacelist,
  3273. packet_mark: pktmark,
  3274. connection_mark: connmark,
  3275. routing_mark: routingmark,
  3276. connection_type: conntype,
  3277. connection_state: states,
  3278. connection_nat_state: natStates,
  3279. src_address_list: srclist,
  3280. dst_address_list: dstlist,
  3281. src_geoip: srcgeo,
  3282. dst_geoip: dstgeo,
  3283. comment,
  3284. disabled: !enabled,
  3285. // Advanced tab
  3286. layer7_protocol: getFwFieldVal('layer7', false),
  3287. content: getFwFieldVal('content', false),
  3288. connection_bytes: getFwFieldVal('connbytes', false),
  3289. connection_rate: getFwFieldVal('connrate', false),
  3290. pcc: getFwFieldVal('pcc', false),
  3291. src_mac_address: getFwFieldVal('srcmac', true),
  3292. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3293. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3294. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3295. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3296. ipsec_policy: getFwFieldVal('ipsec', false),
  3297. tls_host: getFwFieldVal('tlshost', false),
  3298. ingress_priority: getFwFieldVal('ingresspriority', false),
  3299. priority: getFwFieldVal('priority', false),
  3300. dscp: getFwFieldVal('dscp', false),
  3301. tcp_mss: getFwFieldVal('tcpmss', false),
  3302. tos: document.getElementById('fw-val-tos')?.value || '',
  3303. packet_size: getFwFieldVal('pktsize', false),
  3304. random: getFwFieldVal('random', false),
  3305. tcp_flags: getFwFieldVal('tcpflags', false),
  3306. icmp_options: getFwFieldVal('icmpoptions', false),
  3307. ipv4_options: getFwFieldVal('ipv4options', false),
  3308. ttl: getFwFieldVal('ttl', false),
  3309. // Extra tab
  3310. time: getFwFieldVal('time', false),
  3311. limit: getFwFieldVal('limit', false),
  3312. dst_limit: getFwFieldVal('dstlimit', false),
  3313. psd: getFwFieldVal('psd', false),
  3314. // Action tab
  3315. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3316. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3317. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3318. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3319. log: document.getElementById('filter-modal-log')?.checked || false,
  3320. log_prefix: getFwFieldVal('logprefix', false)
  3321. };
  3322. try {
  3323. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3324. method: 'POST',
  3325. headers: { 'Content-Type': 'application/json' },
  3326. body: JSON.stringify(payload)
  3327. });
  3328. if (res.ok) {
  3329. const data = await res.json();
  3330. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3331. loadFirewall(false);
  3332. if (closeAfter) {
  3333. closeFilterModal();
  3334. } else {
  3335. if (data.id) {
  3336. document.getElementById('filter-modal-id').value = data.id;
  3337. const badge = document.getElementById('fw-modal-badge');
  3338. if (badge) badge.innerText = `#${data.id}`;
  3339. }
  3340. }
  3341. } else {
  3342. const err = await res.json();
  3343. showToast('Error', err.message || 'Failed to save rule', 'error');
  3344. }
  3345. } catch (err) {
  3346. showToast('Error', err.message, 'error');
  3347. }
  3348. }
  3349. function submitSaveFilterRule(e) {
  3350. if (e && e.preventDefault) e.preventDefault();
  3351. return applyFilterRule(true);
  3352. }
  3353. function startFwStatPolling() {
  3354. stopFwStatPolling();
  3355. pollRuleStats();
  3356. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3357. }
  3358. function stopFwStatPolling() {
  3359. if (state.fwStatInterval) {
  3360. clearInterval(state.fwStatInterval);
  3361. state.fwStatInterval = null;
  3362. }
  3363. }
  3364. async function pollRuleStats() {
  3365. const id = document.getElementById('filter-modal-id')?.value;
  3366. if (!id) {
  3367. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3368. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3369. return;
  3370. }
  3371. try {
  3372. const res = await fetch(`${API_BASE}/firewall/filter`);
  3373. if (!res.ok) return;
  3374. const rules = await res.json();
  3375. const r = rules.find(x => x.id === id);
  3376. if (!r) return;
  3377. const now = Date.now();
  3378. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3379. state.fwLastTimestamp = now;
  3380. const curBytes = r.bytes || 0;
  3381. const curPackets = r.packets || 0;
  3382. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3383. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3384. state.fwLastBytes = curBytes;
  3385. state.fwLastPackets = curPackets;
  3386. const rateBps = Math.round((deltaBytes * 8) / dt);
  3387. const ratePkt = Math.round(deltaPkts / dt);
  3388. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3389. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3390. state.fwStatRateHistory.push(rateBps);
  3391. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3392. state.fwStatPktHistory.push(ratePkt);
  3393. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3394. const bEl = document.getElementById('fw-stat-bytes');
  3395. const pEl = document.getElementById('fw-stat-packets');
  3396. const rEl = document.getElementById('fw-stat-rate');
  3397. const prEl = document.getElementById('fw-stat-pktrate');
  3398. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3399. if (pEl) pEl.value = curPackets.toLocaleString();
  3400. if (rEl) rEl.value = formatBps(rateBps);
  3401. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3402. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3403. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3404. } catch (e) {
  3405. console.error('Error polling rule stats', e);
  3406. }
  3407. }
  3408. function formatBps(bps) {
  3409. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3410. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3411. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3412. return bps + ' bps';
  3413. }
  3414. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3415. const svg = document.getElementById(svgId);
  3416. if (!svg) return;
  3417. const w = 500;
  3418. const h = 100;
  3419. const paddingRight = 45;
  3420. const graphWidth = w - paddingRight;
  3421. const maxVal = Math.max(5, ...dataArray);
  3422. const currentVal = dataArray[dataArray.length - 1] || 0;
  3423. const leg = document.getElementById(legendId);
  3424. if (leg) {
  3425. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3426. }
  3427. let gridLines = '';
  3428. for (let i = 0; i <= 5; i++) {
  3429. const y = 8 + (i * (h - 18) / 5);
  3430. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3431. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3432. gridLines += `
  3433. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3434. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3435. `;
  3436. }
  3437. const step = graphWidth / (dataArray.length - 1);
  3438. const points = dataArray.map((val, idx) => {
  3439. const x = idx * step;
  3440. const y = (h - 10) - (val / maxVal) * (h - 20);
  3441. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3442. });
  3443. const polylineStr = points.join(' ');
  3444. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3445. svg.innerHTML = `
  3446. ${gridLines}
  3447. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3448. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3449. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3450. `;
  3451. }
  3452. async function moveFilterRule(id, dir) {
  3453. try {
  3454. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3455. method: 'POST',
  3456. headers: { 'Content-Type': 'application/json' },
  3457. body: JSON.stringify({ direction: dir })
  3458. });
  3459. if (res.ok) loadFirewall(false);
  3460. } catch (err) {
  3461. showToast('Error', err.message, 'error');
  3462. }
  3463. }
  3464. async function toggleFilterRuleState(id, disabled) {
  3465. try {
  3466. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3467. method: 'POST',
  3468. headers: { 'Content-Type': 'application/json' },
  3469. body: JSON.stringify({ disabled })
  3470. });
  3471. if (res.ok) loadFirewall(false);
  3472. } catch (err) {
  3473. showToast('Error', err.message, 'error');
  3474. }
  3475. }
  3476. async function deleteFilterRule(id) {
  3477. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3478. try {
  3479. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3480. if (res.ok) {
  3481. showToast('Deleted', 'Filter rule removed', 'success');
  3482. loadFirewall(false);
  3483. }
  3484. } catch (err) {
  3485. showToast('Error', err.message, 'error');
  3486. }
  3487. }
  3488. // ----------------- NAT Rules -----------------
  3489. function renderNATRules() {
  3490. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3491. const tbody = document.getElementById('nat-table-body');
  3492. const empty = document.getElementById('nat-empty');
  3493. if (!tbody) return;
  3494. tbody.innerHTML = '';
  3495. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3496. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3497. if (rules.length === 0) {
  3498. empty?.classList.remove('hidden');
  3499. return;
  3500. }
  3501. empty?.classList.add('hidden');
  3502. rules.forEach((r, idx) => {
  3503. const tr = document.createElement('tr');
  3504. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3505. let toTarget = '-';
  3506. if (r.action === 'jump') {
  3507. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3508. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3509. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3510. } else if (r.action === 'redirect') {
  3511. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3512. } else if (r.action === 'masquerade') {
  3513. 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>`;
  3514. } else if (r.action === 'log') {
  3515. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3516. } else {
  3517. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3518. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3519. }
  3520. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3521. tr.innerHTML = `
  3522. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3523. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3524. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3525. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3526. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3527. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3528. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3529. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3530. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3531. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3532. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3533. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3534. </td>
  3535. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3536. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3537. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3538. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3539. <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>
  3540. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3541. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3542. </td>
  3543. `;
  3544. tbody.appendChild(tr);
  3545. });
  3546. }
  3547. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3548. function switchNATRuleTab(tab) {
  3549. state.activeNATRuleTab = tab;
  3550. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3551. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3552. btn.classList.add('text-slate-400', 'border-transparent');
  3553. });
  3554. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3555. if (activeBtn) {
  3556. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3557. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3558. }
  3559. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3560. const activePane = document.getElementById(`nat-pane-${tab}`);
  3561. if (activePane) activePane.classList.remove('hidden');
  3562. if (tab === 'statistics') {
  3563. startNATStatPolling();
  3564. } else {
  3565. stopNATStatPolling();
  3566. }
  3567. }
  3568. function toggleNATField(fieldKey, expand) {
  3569. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3570. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3571. if (!plusBtn || !fieldBox) return;
  3572. if (expand) {
  3573. plusBtn.classList.add('hidden');
  3574. fieldBox.classList.remove('hidden');
  3575. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3576. if (valInput) valInput.focus();
  3577. } else {
  3578. fieldBox.classList.add('hidden');
  3579. plusBtn.classList.remove('hidden');
  3580. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3581. if (valInput) {
  3582. if (valInput.tagName === 'SELECT') {
  3583. valInput.selectedIndex = 0;
  3584. } else {
  3585. valInput.value = '';
  3586. }
  3587. }
  3588. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3589. if (invInput) invInput.checked = false;
  3590. if (fieldKey === 'days') {
  3591. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3592. const el = document.getElementById(`nat-day-${d}`);
  3593. if (el) el.checked = true;
  3594. });
  3595. }
  3596. }
  3597. }
  3598. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3599. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3600. toggleNATField(fieldKey, true);
  3601. let strVal = String(value);
  3602. if (hasInvert) {
  3603. const inv = strVal.startsWith('!');
  3604. if (inv) strVal = strVal.slice(1);
  3605. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3606. if (invEl) invEl.checked = inv;
  3607. }
  3608. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3609. if (valEl) valEl.value = strVal;
  3610. } else {
  3611. toggleNATField(fieldKey, false);
  3612. }
  3613. }
  3614. function getNATFieldVal(fieldKey, hasInvert = false) {
  3615. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3616. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3617. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3618. let v = valEl ? valEl.value.trim() : '';
  3619. if (!v) return '';
  3620. if (hasInvert) {
  3621. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3622. if (invEl && invEl.checked) {
  3623. v = '!' + v.replace(/^!/, '');
  3624. }
  3625. }
  3626. return v;
  3627. }
  3628. function toggleMaximizeNATModal() {
  3629. const win = document.getElementById('nat-modal-window');
  3630. if (!win) return;
  3631. if (win.classList.contains('max-w-[720px]')) {
  3632. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3633. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3634. } else {
  3635. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3636. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3637. }
  3638. }
  3639. function handleNATChainChange() {
  3640. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3641. const actSel = document.getElementById('nat-modal-action');
  3642. if (actSel) {
  3643. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3644. actSel.value = 'masquerade';
  3645. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3646. actSel.value = 'dst-nat';
  3647. }
  3648. }
  3649. toggleNATActionFields();
  3650. }
  3651. function toggleNATActionFields() {
  3652. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3653. const rowAddr = document.getElementById('nat-row-toaddr');
  3654. const rowPort = document.getElementById('nat-row-toport');
  3655. const jumpBox = document.getElementById('nat-action-jump-box');
  3656. const addrBox = document.getElementById('nat-action-addrlist-box');
  3657. // Hide all dynamic rows first
  3658. if (rowAddr) rowAddr.classList.add('hidden');
  3659. if (rowPort) rowPort.classList.add('hidden');
  3660. if (jumpBox) jumpBox.classList.add('hidden');
  3661. if (addrBox) addrBox.classList.add('hidden');
  3662. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3663. if (rowAddr) rowAddr.classList.remove('hidden');
  3664. if (rowPort) rowPort.classList.remove('hidden');
  3665. } else if (act === 'redirect' || act === 'masquerade') {
  3666. if (rowPort) rowPort.classList.remove('hidden');
  3667. } else if (act === 'jump') {
  3668. if (jumpBox) jumpBox.classList.remove('hidden');
  3669. } else if (act.includes('address-list') || act.includes('address list')) {
  3670. if (addrBox) addrBox.classList.remove('hidden');
  3671. }
  3672. if (act === 'log') {
  3673. const logEl = document.getElementById('nat-modal-log');
  3674. if (logEl) logEl.checked = true;
  3675. toggleNATField('logprefix', true);
  3676. }
  3677. }
  3678. function toggleNATLogPrefix() {
  3679. const isLog = document.getElementById('nat-modal-log')?.checked;
  3680. toggleNATField('logprefix', !!isLog);
  3681. }
  3682. function openAddNATModal() {
  3683. switchNATRuleTab('general');
  3684. const badge = document.getElementById('nat-modal-badge');
  3685. if (badge) badge.innerText = 'New...';
  3686. document.getElementById('nat-modal-id').value = '';
  3687. document.getElementById('nat-modal-enabled').checked = true;
  3688. document.getElementById('nat-modal-comment').value = '';
  3689. document.getElementById('nat-modal-chain').value = 'srcnat';
  3690. document.getElementById('nat-modal-action').value = 'masquerade';
  3691. document.getElementById('nat-modal-toaddr').value = '';
  3692. document.getElementById('nat-modal-toport').value = '';
  3693. document.getElementById('nat-modal-log').checked = false;
  3694. populateInterfaceSelect('nat-val-iniface');
  3695. populateInterfaceSelect('nat-val-outiface');
  3696. populateAddressListSelect('nat-val-srclist');
  3697. populateAddressListSelect('nat-val-dstlist');
  3698. populateGeoIPSelect('nat-val-srcgeo');
  3699. populateGeoIPSelect('nat-val-dstgeo');
  3700. const allFieldKeys = [
  3701. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3702. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3703. 'routingmark', 'conntype',
  3704. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3705. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3706. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3707. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3708. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3709. ];
  3710. allFieldKeys.forEach(k => toggleNATField(k, false));
  3711. resetCurrentNATRuleCounters();
  3712. toggleNATActionFields();
  3713. document.getElementById('nat-modal').classList.remove('hidden');
  3714. }
  3715. function openEditNATModal(id) {
  3716. const r = (state.natRules || []).find(rule => rule.id === id);
  3717. if (!r) return;
  3718. switchNATRuleTab('general');
  3719. const badge = document.getElementById('nat-modal-badge');
  3720. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3721. document.getElementById('nat-modal-id').value = r.id;
  3722. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3723. document.getElementById('nat-modal-comment').value = r.comment || '';
  3724. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3725. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3726. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3727. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3728. document.getElementById('nat-modal-log').checked = !!r.log;
  3729. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3730. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3731. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3732. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3733. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3734. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3735. setNATFieldVal('src', r.src_address, true);
  3736. setNATFieldVal('dst', r.dst_address, true);
  3737. setNATFieldVal('srclist', r.src_address_list, true);
  3738. setNATFieldVal('dstlist', r.dst_address_list, true);
  3739. setNATFieldVal('srcgeo', r.src_geoip, true);
  3740. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3741. if (r.protocol && r.protocol !== 'all') {
  3742. setNATFieldVal('proto', r.protocol, true);
  3743. } else {
  3744. toggleNATField('proto', false);
  3745. }
  3746. setNATFieldVal('sport', r.src_port, true);
  3747. setNATFieldVal('dport', r.dst_port, true);
  3748. setNATFieldVal('anyport', r.any_port, true);
  3749. setNATFieldVal('iniface', r.in_interface, true);
  3750. setNATFieldVal('outiface', r.out_interface, true);
  3751. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3752. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3753. setNATFieldVal('pktmark', r.packet_mark, true);
  3754. setNATFieldVal('connmark', r.connection_mark, true);
  3755. setNATFieldVal('routingmark', r.routing_mark, true);
  3756. setNATFieldVal('conntype', r.connection_type, false);
  3757. // Advanced tab fields
  3758. setNATFieldVal('layer7', r.layer7_protocol, false);
  3759. setNATFieldVal('content', r.content, false);
  3760. setNATFieldVal('connbytes', r.connection_bytes, false);
  3761. setNATFieldVal('connrate', r.connection_rate, false);
  3762. setNATFieldVal('pcc', r.pcc, false);
  3763. setNATFieldVal('srcmac', r.src_mac_address, true);
  3764. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3765. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3766. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3767. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3768. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3769. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3770. setNATFieldVal('priority', r.priority, false);
  3771. setNATFieldVal('dscp', r.dscp, false);
  3772. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3773. if (r.tos) {
  3774. const tosEl = document.getElementById('nat-val-tos');
  3775. if (tosEl) tosEl.value = r.tos;
  3776. }
  3777. setNATFieldVal('pktsize', r.packet_size, false);
  3778. setNATFieldVal('random', r.random, false);
  3779. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3780. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3781. setNATFieldVal('ttl', r.ttl, false);
  3782. // Extra tab fields
  3783. setNATFieldVal('time', r.time, false);
  3784. if (r.days) {
  3785. toggleNATField('days', true);
  3786. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3787. const chk = document.getElementById(`nat-day-${d}`);
  3788. if (chk) chk.checked = r.days.includes(d);
  3789. });
  3790. } else {
  3791. toggleNATField('days', false);
  3792. }
  3793. setNATFieldVal('limit', r.limit, false);
  3794. setNATFieldVal('dstlimit', r.dst_limit, false);
  3795. setNATFieldVal('psd', r.psd, false);
  3796. // Action fields
  3797. if (r.jump_target) {
  3798. const jtEl = document.getElementById('nat-modal-jumptarget');
  3799. if (jtEl) jtEl.value = r.jump_target;
  3800. }
  3801. if (r.address_list) {
  3802. const alEl = document.getElementById('nat-modal-action-addrlist');
  3803. if (alEl) alEl.value = r.address_list;
  3804. }
  3805. if (r.address_list_timeout) {
  3806. const toEl = document.getElementById('nat-modal-action-timeout');
  3807. if (toEl) toEl.value = r.address_list_timeout;
  3808. }
  3809. setNATFieldVal('logprefix', r.log_prefix, false);
  3810. // Statistics
  3811. const bEl = document.getElementById('nat-stat-bytes');
  3812. const pEl = document.getElementById('nat-stat-packets');
  3813. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3814. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3815. state.natLastBytes = r.bytes || 0;
  3816. state.natLastPackets = r.packets || 0;
  3817. state.natLastTimestamp = Date.now();
  3818. state.natStatRateHistory = new Array(30).fill(0);
  3819. state.natStatPktHistory = new Array(30).fill(0);
  3820. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3821. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3822. toggleNATActionFields();
  3823. document.getElementById('nat-modal').classList.remove('hidden');
  3824. }
  3825. function closeNATModal() {
  3826. stopNATStatPolling();
  3827. document.getElementById('nat-modal').classList.add('hidden');
  3828. }
  3829. function copyNATRule() {
  3830. document.getElementById('nat-modal-id').value = '';
  3831. const badge = document.getElementById('nat-modal-badge');
  3832. if (badge) badge.innerText = 'New...';
  3833. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3834. }
  3835. function resetCurrentNATRuleCounters() {
  3836. state.natStatRateHistory = new Array(30).fill(0);
  3837. state.natStatPktHistory = new Array(30).fill(0);
  3838. state.natLastBytes = 0;
  3839. state.natLastPackets = 0;
  3840. state.natLastTimestamp = Date.now();
  3841. const bEl = document.getElementById('nat-stat-bytes');
  3842. const pEl = document.getElementById('nat-stat-packets');
  3843. const rEl = document.getElementById('nat-stat-rate');
  3844. const prEl = document.getElementById('nat-stat-pktrate');
  3845. if (bEl) bEl.value = '0 B';
  3846. if (pEl) pEl.value = '0';
  3847. if (rEl) rEl.value = '0 bps';
  3848. if (prEl) prEl.value = '0 p/s';
  3849. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3850. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3851. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3852. }
  3853. async function applyNATRule(closeAfter = false) {
  3854. const id = document.getElementById('nat-modal-id').value;
  3855. const chain = document.getElementById('nat-modal-chain').value;
  3856. const action = document.getElementById('nat-modal-action').value;
  3857. const comment = document.getElementById('nat-modal-comment').value.trim();
  3858. const enabled = document.getElementById('nat-modal-enabled').checked;
  3859. const src = getNATFieldVal('src', true);
  3860. const dst = getNATFieldVal('dst', true);
  3861. const srclist = getNATFieldVal('srclist', true);
  3862. const dstlist = getNATFieldVal('dstlist', true);
  3863. const srcgeo = getNATFieldVal('srcgeo', true);
  3864. const dstgeo = getNATFieldVal('dstgeo', true);
  3865. const proto = getNATFieldVal('proto', true);
  3866. const sport = getNATFieldVal('sport', true);
  3867. const dport = getNATFieldVal('dport', true);
  3868. const anyport = getNATFieldVal('anyport', true);
  3869. const iniface = getNATFieldVal('iniface', true);
  3870. const outiface = getNATFieldVal('outiface', true);
  3871. const inifacelist = getNATFieldVal('inifacelist', true);
  3872. const outifacelist = getNATFieldVal('outifacelist', true);
  3873. const pktmark = getNATFieldVal('pktmark', true);
  3874. const connmark = getNATFieldVal('connmark', true);
  3875. const routingmark = getNATFieldVal('routingmark', true);
  3876. const conntype = getNATFieldVal('conntype', false);
  3877. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3878. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3879. const payload = {
  3880. id,
  3881. chain,
  3882. action,
  3883. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3884. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3885. protocol: proto || 'all',
  3886. src_address: src,
  3887. dst_address: dst,
  3888. src_port: sport,
  3889. dst_port: dport,
  3890. any_port: anyport,
  3891. in_interface: iniface,
  3892. out_interface: outiface,
  3893. in_interface_list: inifacelist,
  3894. out_interface_list: outifacelist,
  3895. packet_mark: pktmark,
  3896. connection_mark: connmark,
  3897. routing_mark: routingmark,
  3898. connection_type: conntype,
  3899. src_address_list: srclist,
  3900. dst_address_list: dstlist,
  3901. src_geoip: srcgeo,
  3902. dst_geoip: dstgeo,
  3903. comment,
  3904. disabled: !enabled,
  3905. // Advanced tab
  3906. layer7_protocol: getNATFieldVal('layer7', false),
  3907. content: getNATFieldVal('content', false),
  3908. connection_bytes: getNATFieldVal('connbytes', false),
  3909. connection_rate: getNATFieldVal('connrate', false),
  3910. pcc: getNATFieldVal('pcc', false),
  3911. src_mac_address: getNATFieldVal('srcmac', true),
  3912. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3913. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3914. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3915. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3916. ipsec_policy: getNATFieldVal('ipsec', false),
  3917. ingress_priority: getNATFieldVal('ingresspriority', false),
  3918. priority: getNATFieldVal('priority', false),
  3919. dscp: getNATFieldVal('dscp', false),
  3920. tcp_mss: getNATFieldVal('tcpmss', false),
  3921. tos: document.getElementById('nat-val-tos')?.value || '',
  3922. packet_size: getNATFieldVal('pktsize', false),
  3923. random: getNATFieldVal('random', false),
  3924. icmp_options: getNATFieldVal('icmpoptions', false),
  3925. ipv4_options: getNATFieldVal('ipv4options', false),
  3926. ttl: getNATFieldVal('ttl', false),
  3927. // Extra tab
  3928. time: getNATFieldVal('time', false),
  3929. limit: getNATFieldVal('limit', false),
  3930. dst_limit: getNATFieldVal('dstlimit', false),
  3931. psd: getNATFieldVal('psd', false),
  3932. // Action tab
  3933. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3934. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3935. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3936. log: document.getElementById('nat-modal-log')?.checked || false,
  3937. log_prefix: getNATFieldVal('logprefix', false)
  3938. };
  3939. try {
  3940. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3941. method: 'POST',
  3942. headers: { 'Content-Type': 'application/json' },
  3943. body: JSON.stringify(payload)
  3944. });
  3945. if (res.ok) {
  3946. const data = await res.json();
  3947. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3948. loadFirewall(false);
  3949. if (closeAfter) {
  3950. closeNATModal();
  3951. } else {
  3952. if (data.id) {
  3953. document.getElementById('nat-modal-id').value = data.id;
  3954. const badge = document.getElementById('nat-modal-badge');
  3955. if (badge) badge.innerText = `#${data.id}`;
  3956. }
  3957. }
  3958. } else {
  3959. const err = await res.json();
  3960. showToast('Error', err.message || 'Failed to save rule', 'error');
  3961. }
  3962. } catch (err) {
  3963. showToast('Error', err.message, 'error');
  3964. }
  3965. }
  3966. function submitSaveNATRule(e) {
  3967. if (e && e.preventDefault) e.preventDefault();
  3968. return applyNATRule(true);
  3969. }
  3970. function startNATStatPolling() {
  3971. stopNATStatPolling();
  3972. pollNATRuleStats();
  3973. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3974. }
  3975. function stopNATStatPolling() {
  3976. if (state.natStatInterval) {
  3977. clearInterval(state.natStatInterval);
  3978. state.natStatInterval = null;
  3979. }
  3980. }
  3981. async function pollNATRuleStats() {
  3982. const id = document.getElementById('nat-modal-id')?.value;
  3983. if (!id) {
  3984. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3985. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3986. return;
  3987. }
  3988. try {
  3989. const res = await fetch(`${API_BASE}/firewall/nat`);
  3990. if (!res.ok) return;
  3991. const rules = await res.json();
  3992. const r = rules.find(x => x.id === id);
  3993. if (!r) return;
  3994. const now = Date.now();
  3995. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3996. state.natLastTimestamp = now;
  3997. const curBytes = r.bytes || 0;
  3998. const curPackets = r.packets || 0;
  3999. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4000. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4001. state.natLastBytes = curBytes;
  4002. state.natLastPackets = curPackets;
  4003. const rateBps = Math.round((deltaBytes * 8) / dt);
  4004. const ratePkt = Math.round(deltaPkts / dt);
  4005. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4006. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4007. state.natStatRateHistory.push(rateBps);
  4008. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4009. state.natStatPktHistory.push(ratePkt);
  4010. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4011. const bEl = document.getElementById('nat-stat-bytes');
  4012. const pEl = document.getElementById('nat-stat-packets');
  4013. const rEl = document.getElementById('nat-stat-rate');
  4014. const prEl = document.getElementById('nat-stat-pktrate');
  4015. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4016. if (pEl) pEl.value = curPackets.toLocaleString();
  4017. if (rEl) rEl.value = formatBps(rateBps);
  4018. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4019. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4020. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4021. } catch (e) {
  4022. console.error('Error polling NAT rule stats', e);
  4023. }
  4024. }
  4025. async function moveNATRule(id, dir) {
  4026. try {
  4027. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4028. method: 'POST',
  4029. headers: { 'Content-Type': 'application/json' },
  4030. body: JSON.stringify({ direction: dir })
  4031. });
  4032. if (res.ok) loadFirewall(false);
  4033. } catch (err) {
  4034. showToast('Error', err.message, 'error');
  4035. }
  4036. }
  4037. async function toggleNATRuleState(id, disabled) {
  4038. try {
  4039. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4040. method: 'POST',
  4041. headers: { 'Content-Type': 'application/json' },
  4042. body: JSON.stringify({ disabled })
  4043. });
  4044. if (res.ok) loadFirewall(false);
  4045. } catch (err) {
  4046. showToast('Error', err.message, 'error');
  4047. }
  4048. }
  4049. async function deleteNATRule(id) {
  4050. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4051. try {
  4052. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4053. if (res.ok) {
  4054. showToast('Deleted', 'NAT rule removed', 'success');
  4055. loadFirewall(false);
  4056. }
  4057. } catch (err) {
  4058. showToast('Error', err.message, 'error');
  4059. }
  4060. }
  4061. // ----------------- Mangle Rules -----------------
  4062. function renderMangleRules() {
  4063. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4064. const tbody = document.getElementById('mangle-table-body');
  4065. const empty = document.getElementById('mangle-empty');
  4066. if (!tbody) return;
  4067. tbody.innerHTML = '';
  4068. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4069. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4070. if (rules.length === 0) {
  4071. empty?.classList.remove('hidden');
  4072. return;
  4073. }
  4074. empty?.classList.add('hidden');
  4075. rules.forEach((r, idx) => {
  4076. const tr = document.createElement('tr');
  4077. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4078. let markVal = '<span class="text-slate-500">-</span>';
  4079. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4080. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4081. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4082. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4083. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4084. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4085. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4086. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4087. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4088. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4089. 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>`;
  4090. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4091. tr.innerHTML = `
  4092. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4093. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4094. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4095. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4096. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4097. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4098. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4099. <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>
  4100. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4101. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4102. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4103. </td>
  4104. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4105. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4106. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4107. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4108. <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>
  4109. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4110. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4111. </td>
  4112. `;
  4113. tbody.appendChild(tr);
  4114. });
  4115. }
  4116. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4117. function switchMangleRuleTab(tab) {
  4118. state.activeMangleRuleTab = tab;
  4119. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4120. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4121. btn.classList.add('text-slate-400', 'border-transparent');
  4122. });
  4123. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4124. if (activeBtn) {
  4125. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4126. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4127. }
  4128. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4129. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4130. if (activePane) activePane.classList.remove('hidden');
  4131. if (tab === 'statistics') {
  4132. startMangleStatPolling();
  4133. } else {
  4134. stopMangleStatPolling();
  4135. }
  4136. }
  4137. function toggleMangleField(fieldKey, expand) {
  4138. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4139. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4140. if (!plusBtn || !fieldBox) return;
  4141. if (expand) {
  4142. plusBtn.classList.add('hidden');
  4143. fieldBox.classList.remove('hidden');
  4144. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4145. if (valInput) valInput.focus();
  4146. } else {
  4147. fieldBox.classList.add('hidden');
  4148. plusBtn.classList.remove('hidden');
  4149. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4150. if (valInput) {
  4151. if (valInput.tagName === 'SELECT') {
  4152. valInput.selectedIndex = 0;
  4153. } else {
  4154. valInput.value = '';
  4155. }
  4156. }
  4157. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4158. if (invInput) invInput.checked = false;
  4159. if (fieldKey === 'cs') {
  4160. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4161. const el = document.getElementById(id);
  4162. if (el) el.checked = false;
  4163. });
  4164. }
  4165. if (fieldKey === 'natstate') {
  4166. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4167. const el = document.getElementById(id);
  4168. if (el) el.checked = false;
  4169. });
  4170. }
  4171. }
  4172. }
  4173. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4174. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4175. toggleMangleField(fieldKey, true);
  4176. let strVal = String(value);
  4177. if (hasInvert) {
  4178. const inv = strVal.startsWith('!');
  4179. if (inv) strVal = strVal.slice(1);
  4180. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4181. if (invEl) invEl.checked = inv;
  4182. }
  4183. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4184. if (valEl) valEl.value = strVal;
  4185. } else {
  4186. toggleMangleField(fieldKey, false);
  4187. }
  4188. }
  4189. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4190. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4191. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4192. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4193. let v = valEl ? valEl.value.trim() : '';
  4194. if (!v) return '';
  4195. if (hasInvert) {
  4196. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4197. if (invEl && invEl.checked) {
  4198. v = '!' + v.replace(/^!/, '');
  4199. }
  4200. }
  4201. return v;
  4202. }
  4203. function toggleMaximizeMangleModal() {
  4204. const win = document.getElementById('mangle-modal-window');
  4205. if (!win) return;
  4206. if (win.classList.contains('max-w-[720px]')) {
  4207. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4208. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4209. } else {
  4210. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4211. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4212. }
  4213. }
  4214. function toggleMangleActionFields() {
  4215. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4216. // Hide all dynamic rows first
  4217. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4218. const el = document.getElementById(`mangle-row-${id}`);
  4219. if (el) el.classList.add('hidden');
  4220. });
  4221. const jumpBox = document.getElementById('mangle-action-jump-box');
  4222. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4223. if (jumpBox) jumpBox.classList.add('hidden');
  4224. if (addrBox) addrBox.classList.add('hidden');
  4225. // Activate matching rows
  4226. if (act === 'mark-connection') {
  4227. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4228. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4229. } else if (act === 'mark-routing') {
  4230. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4231. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4232. } else if (act === 'mark-packet') {
  4233. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4234. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4235. } else if (act === 'change-mss') {
  4236. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4237. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4238. } else if (act === 'change-dscp') {
  4239. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4240. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4241. } else if (act === 'change-ttl') {
  4242. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4243. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4244. } else if (act === 'set-priority') {
  4245. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4246. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4247. } else if (act === 'route') {
  4248. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4249. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4250. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4251. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4252. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4253. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4254. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4255. } else if (act === 'jump') {
  4256. if (jumpBox) jumpBox.classList.remove('hidden');
  4257. } else if (act.includes('address-list') || act.includes('address list')) {
  4258. if (addrBox) addrBox.classList.remove('hidden');
  4259. }
  4260. if (act === 'log') {
  4261. const logEl = document.getElementById('mangle-modal-log');
  4262. if (logEl) logEl.checked = true;
  4263. toggleMangleField('logprefix', true);
  4264. }
  4265. }
  4266. function toggleMangleLogPrefix() {
  4267. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4268. toggleMangleField('logprefix', !!isLog);
  4269. }
  4270. const allMangleFieldKeys = [
  4271. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4272. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4273. 'routingmark', 'conntype', 'cs', 'natstate',
  4274. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4275. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4276. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4277. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4278. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4279. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4280. ];
  4281. function openAddMangleModal() {
  4282. switchMangleRuleTab('general');
  4283. const badge = document.getElementById('mangle-modal-badge');
  4284. if (badge) badge.innerText = 'New...';
  4285. document.getElementById('mangle-modal-id').value = '';
  4286. document.getElementById('mangle-modal-enabled').checked = true;
  4287. document.getElementById('mangle-modal-comment').value = '';
  4288. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4289. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4290. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4291. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4292. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4293. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4294. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4295. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4296. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4297. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4298. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4299. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4300. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4301. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4302. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4303. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4304. populateInterfaceSelect('mangle-val-iniface');
  4305. populateInterfaceSelect('mangle-val-outiface');
  4306. populateAddressListSelect('mangle-val-srclist');
  4307. populateAddressListSelect('mangle-val-dstlist');
  4308. populateGeoIPSelect('mangle-val-srcgeo');
  4309. populateGeoIPSelect('mangle-val-dstgeo');
  4310. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4311. resetCurrentMangleRuleCounters();
  4312. toggleMangleActionFields();
  4313. document.getElementById('mangle-modal').classList.remove('hidden');
  4314. }
  4315. function openEditMangleModal(id) {
  4316. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4317. if (!r) return;
  4318. switchMangleRuleTab('general');
  4319. const badge = document.getElementById('mangle-modal-badge');
  4320. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4321. document.getElementById('mangle-modal-id').value = r.id;
  4322. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4323. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4324. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4325. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4326. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4327. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4328. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4329. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4330. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4331. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4332. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4333. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4334. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4335. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4336. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4337. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4338. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4339. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4340. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4341. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4342. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4343. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4344. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4345. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4346. setMangleFieldVal('src', r.src_address, true);
  4347. setMangleFieldVal('dst', r.dst_address, true);
  4348. setMangleFieldVal('srclist', r.src_address_list, true);
  4349. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4350. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4351. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4352. if (r.protocol && r.protocol !== 'all') {
  4353. setMangleFieldVal('proto', r.protocol, true);
  4354. } else {
  4355. toggleMangleField('proto', false);
  4356. }
  4357. setMangleFieldVal('sport', r.src_port, true);
  4358. setMangleFieldVal('dport', r.dst_port, true);
  4359. setMangleFieldVal('anyport', r.any_port, true);
  4360. setMangleFieldVal('iniface', r.in_interface, true);
  4361. setMangleFieldVal('outiface', r.out_interface, true);
  4362. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4363. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4364. setMangleFieldVal('pktmark', r.packet_mark, true);
  4365. setMangleFieldVal('connmark', r.connection_mark, true);
  4366. setMangleFieldVal('routingmark', r.routing_mark, true);
  4367. setMangleFieldVal('conntype', r.connection_type, false);
  4368. // Connection State
  4369. const states = r.connection_state || [];
  4370. if (states.length > 0) {
  4371. toggleMangleField('cs', true);
  4372. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4373. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4374. if (el) el.checked = states.includes(s);
  4375. });
  4376. } else {
  4377. toggleMangleField('cs', false);
  4378. }
  4379. // Connection NAT State
  4380. const natStates = r.connection_nat_state || [];
  4381. if (natStates.length > 0) {
  4382. toggleMangleField('natstate', true);
  4383. ['srcnat', 'dstnat'].forEach(s => {
  4384. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4385. if (el) el.checked = natStates.includes(s);
  4386. });
  4387. } else {
  4388. toggleMangleField('natstate', false);
  4389. }
  4390. // Advanced tab fields
  4391. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4392. setMangleFieldVal('content', r.content, false);
  4393. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4394. setMangleFieldVal('connrate', r.connection_rate, false);
  4395. setMangleFieldVal('pcc', r.pcc, false);
  4396. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4397. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4398. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4399. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4400. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4401. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4402. setMangleFieldVal('tlshost', r.tls_host, false);
  4403. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4404. setMangleFieldVal('priority', r.priority, false);
  4405. setMangleFieldVal('dscp', r.dscp, false);
  4406. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4407. if (r.tos) {
  4408. const tosEl = document.getElementById('mangle-val-tos');
  4409. if (tosEl) tosEl.value = r.tos;
  4410. }
  4411. setMangleFieldVal('pktsize', r.packet_size, false);
  4412. setMangleFieldVal('random', r.random, false);
  4413. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4414. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4415. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4416. setMangleFieldVal('ttl', r.ttl, false);
  4417. // Extra tab fields
  4418. setMangleFieldVal('nth', r.nth, false);
  4419. setMangleFieldVal('connlimit', r.connection_limit, false);
  4420. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4421. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4422. setMangleFieldVal('hotspot', r.hotspot, false);
  4423. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4424. setMangleFieldVal('limit', r.limit, false);
  4425. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4426. setMangleFieldVal('time', r.time, false);
  4427. setMangleFieldVal('psd', r.psd, false);
  4428. // Action fields
  4429. if (r.jump_target) {
  4430. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4431. if (jtEl) jtEl.value = r.jump_target;
  4432. }
  4433. if (r.address_list) {
  4434. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4435. if (alEl) alEl.value = r.address_list;
  4436. }
  4437. if (r.address_list_timeout) {
  4438. const toEl = document.getElementById('mangle-modal-action-timeout');
  4439. if (toEl) toEl.value = r.address_list_timeout;
  4440. }
  4441. setMangleFieldVal('logprefix', r.log_prefix, false);
  4442. // Statistics
  4443. const bEl = document.getElementById('mangle-stat-bytes');
  4444. const pEl = document.getElementById('mangle-stat-packets');
  4445. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4446. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4447. state.mangleLastBytes = r.bytes || 0;
  4448. state.mangleLastPackets = r.packets || 0;
  4449. state.mangleLastTimestamp = Date.now();
  4450. state.mangleStatRateHistory = new Array(30).fill(0);
  4451. state.mangleStatPktHistory = new Array(30).fill(0);
  4452. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4453. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4454. toggleMangleActionFields();
  4455. document.getElementById('mangle-modal').classList.remove('hidden');
  4456. }
  4457. function closeMangleModal() {
  4458. stopMangleStatPolling();
  4459. document.getElementById('mangle-modal').classList.add('hidden');
  4460. }
  4461. function copyMangleRule() {
  4462. document.getElementById('mangle-modal-id').value = '';
  4463. const badge = document.getElementById('mangle-modal-badge');
  4464. if (badge) badge.innerText = 'New...';
  4465. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4466. }
  4467. function resetCurrentMangleRuleCounters() {
  4468. state.mangleStatRateHistory = new Array(30).fill(0);
  4469. state.mangleStatPktHistory = new Array(30).fill(0);
  4470. state.mangleLastBytes = 0;
  4471. state.mangleLastPackets = 0;
  4472. state.mangleLastTimestamp = Date.now();
  4473. const bEl = document.getElementById('mangle-stat-bytes');
  4474. const pEl = document.getElementById('mangle-stat-packets');
  4475. const rEl = document.getElementById('mangle-stat-rate');
  4476. const prEl = document.getElementById('mangle-stat-pktrate');
  4477. if (bEl) bEl.value = '0 B';
  4478. if (pEl) pEl.value = '0';
  4479. if (rEl) rEl.value = '0 bps';
  4480. if (prEl) prEl.value = '0 p/s';
  4481. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4482. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4483. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4484. }
  4485. async function applyMangleRule(closeAfter = false) {
  4486. const id = document.getElementById('mangle-modal-id').value;
  4487. const chain = document.getElementById('mangle-modal-chain').value;
  4488. const action = document.getElementById('mangle-modal-action').value;
  4489. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4490. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4491. const src = getMangleFieldVal('src', true);
  4492. const dst = getMangleFieldVal('dst', true);
  4493. const srclist = getMangleFieldVal('srclist', true);
  4494. const dstlist = getMangleFieldVal('dstlist', true);
  4495. const srcgeo = getMangleFieldVal('srcgeo', true);
  4496. const dstgeo = getMangleFieldVal('dstgeo', true);
  4497. const proto = getMangleFieldVal('proto', true);
  4498. const sport = getMangleFieldVal('sport', true);
  4499. const dport = getMangleFieldVal('dport', true);
  4500. const anyport = getMangleFieldVal('anyport', true);
  4501. const iniface = getMangleFieldVal('iniface', true);
  4502. const outiface = getMangleFieldVal('outiface', true);
  4503. const inifacelist = getMangleFieldVal('inifacelist', true);
  4504. const outifacelist = getMangleFieldVal('outifacelist', true);
  4505. const pktmark = getMangleFieldVal('pktmark', true);
  4506. const connmark = getMangleFieldVal('connmark', true);
  4507. const routingmark = getMangleFieldVal('routingmark', true);
  4508. const conntype = getMangleFieldVal('conntype', false);
  4509. const states = [];
  4510. const csBox = document.getElementById('mangle-field-cs');
  4511. if (csBox && !csBox.classList.contains('hidden')) {
  4512. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4513. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4514. });
  4515. }
  4516. const natStates = [];
  4517. const natBox = document.getElementById('mangle-field-natstate');
  4518. if (natBox && !natBox.classList.contains('hidden')) {
  4519. ['srcnat', 'dstnat'].forEach(s => {
  4520. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4521. });
  4522. }
  4523. const payload = {
  4524. id,
  4525. chain,
  4526. action,
  4527. protocol: proto || 'all',
  4528. src_address: src,
  4529. dst_address: dst,
  4530. src_port: sport,
  4531. dst_port: dport,
  4532. any_port: anyport,
  4533. in_interface: iniface,
  4534. out_interface: outiface,
  4535. in_interface_list: inifacelist,
  4536. out_interface_list: outifacelist,
  4537. packet_mark: pktmark,
  4538. connection_mark: connmark,
  4539. routing_mark: routingmark,
  4540. connection_type: conntype,
  4541. connection_state: states,
  4542. connection_nat_state: natStates,
  4543. src_address_list: srclist,
  4544. dst_address_list: dstlist,
  4545. src_geoip: srcgeo,
  4546. dst_geoip: dstgeo,
  4547. comment,
  4548. disabled: !enabled,
  4549. // Advanced tab
  4550. layer7_protocol: getMangleFieldVal('layer7', false),
  4551. content: getMangleFieldVal('content', false),
  4552. connection_bytes: getMangleFieldVal('connbytes', false),
  4553. connection_rate: getMangleFieldVal('connrate', false),
  4554. pcc: getMangleFieldVal('pcc', false),
  4555. src_mac_address: getMangleFieldVal('srcmac', true),
  4556. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4557. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4558. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4559. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4560. ipsec_policy: getMangleFieldVal('ipsec', false),
  4561. tls_host: getMangleFieldVal('tlshost', false),
  4562. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4563. priority: getMangleFieldVal('priority', false),
  4564. dscp: getMangleFieldVal('dscp', false),
  4565. tcp_mss: getMangleFieldVal('tcpmss', false),
  4566. tos: document.getElementById('mangle-val-tos')?.value || '',
  4567. packet_size: getMangleFieldVal('pktsize', false),
  4568. random: getMangleFieldVal('random', false),
  4569. tcp_flags: getMangleFieldVal('tcpflags', false),
  4570. icmp_options: getMangleFieldVal('icmpoptions', false),
  4571. ipv4_options: getMangleFieldVal('ipv4options', false),
  4572. ttl: getMangleFieldVal('ttl', false),
  4573. // Extra tab
  4574. nth: getMangleFieldVal('nth', false),
  4575. connection_limit: getMangleFieldVal('connlimit', false),
  4576. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4577. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4578. hotspot: getMangleFieldVal('hotspot', false),
  4579. ip_fragment: getMangleFieldVal('ipfragment', false),
  4580. limit: getMangleFieldVal('limit', false),
  4581. dst_limit: getMangleFieldVal('dstlimit', false),
  4582. time: getMangleFieldVal('time', false),
  4583. psd: getMangleFieldVal('psd', false),
  4584. // Action tab
  4585. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4586. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4587. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4588. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4589. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4590. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4591. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4592. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4593. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4594. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4595. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4596. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4597. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4598. log: document.getElementById('mangle-modal-log')?.checked || false,
  4599. log_prefix: getMangleFieldVal('logprefix', false)
  4600. };
  4601. try {
  4602. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4603. method: 'POST',
  4604. headers: { 'Content-Type': 'application/json' },
  4605. body: JSON.stringify(payload)
  4606. });
  4607. if (res.ok) {
  4608. const data = await res.json();
  4609. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4610. loadFirewall(false);
  4611. if (closeAfter) {
  4612. closeMangleModal();
  4613. } else {
  4614. if (data.id) {
  4615. document.getElementById('mangle-modal-id').value = data.id;
  4616. const badge = document.getElementById('mangle-modal-badge');
  4617. if (badge) badge.innerText = `#${data.id}`;
  4618. }
  4619. }
  4620. } else {
  4621. const err = await res.json();
  4622. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4623. }
  4624. } catch (err) {
  4625. showToast('Error', err.message, 'error');
  4626. }
  4627. }
  4628. function submitSaveMangleRule(e) {
  4629. if (e && e.preventDefault) e.preventDefault();
  4630. return applyMangleRule(true);
  4631. }
  4632. function startMangleStatPolling() {
  4633. stopMangleStatPolling();
  4634. pollMangleRuleStats();
  4635. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4636. }
  4637. function stopMangleStatPolling() {
  4638. if (state.mangleStatInterval) {
  4639. clearInterval(state.mangleStatInterval);
  4640. state.mangleStatInterval = null;
  4641. }
  4642. }
  4643. async function pollMangleRuleStats() {
  4644. const id = document.getElementById('mangle-modal-id')?.value;
  4645. if (!id) {
  4646. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4647. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4648. return;
  4649. }
  4650. try {
  4651. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4652. if (!res.ok) return;
  4653. const rules = await res.json();
  4654. const r = rules.find(x => x.id === id);
  4655. if (!r) return;
  4656. const now = Date.now();
  4657. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4658. state.mangleLastTimestamp = now;
  4659. const curBytes = r.bytes || 0;
  4660. const curPackets = r.packets || 0;
  4661. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4662. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4663. state.mangleLastBytes = curBytes;
  4664. state.mangleLastPackets = curPackets;
  4665. const rateBps = Math.round((deltaBytes * 8) / dt);
  4666. const ratePkt = Math.round(deltaPkts / dt);
  4667. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4668. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4669. state.mangleStatRateHistory.push(rateBps);
  4670. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4671. state.mangleStatPktHistory.push(ratePkt);
  4672. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4673. const bEl = document.getElementById('mangle-stat-bytes');
  4674. const pEl = document.getElementById('mangle-stat-packets');
  4675. const rEl = document.getElementById('mangle-stat-rate');
  4676. const prEl = document.getElementById('mangle-stat-pktrate');
  4677. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4678. if (pEl) pEl.value = curPackets.toLocaleString();
  4679. if (rEl) rEl.value = formatBps(rateBps);
  4680. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4681. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4682. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4683. } catch (e) {
  4684. console.error('Error polling Mangle rule stats', e);
  4685. }
  4686. }
  4687. async function moveMangleRule(id, dir) {
  4688. try {
  4689. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4690. method: 'POST',
  4691. headers: { 'Content-Type': 'application/json' },
  4692. body: JSON.stringify({ direction: dir })
  4693. });
  4694. if (res.ok) loadFirewall(false);
  4695. } catch (err) {
  4696. showToast('Error', err.message, 'error');
  4697. }
  4698. }
  4699. async function toggleMangleRuleState(id, disabled) {
  4700. try {
  4701. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4702. method: 'POST',
  4703. headers: { 'Content-Type': 'application/json' },
  4704. body: JSON.stringify({ disabled })
  4705. });
  4706. if (res.ok) loadFirewall(false);
  4707. } catch (err) {
  4708. showToast('Error', err.message, 'error');
  4709. }
  4710. }
  4711. async function deleteMangleRule(id) {
  4712. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4713. try {
  4714. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4715. if (res.ok) {
  4716. showToast('Deleted', 'Mangle rule removed', 'success');
  4717. loadFirewall(false);
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. // ----------------- Address Lists -----------------
  4724. function renderAddressLists() {
  4725. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4726. const tbody = document.getElementById('addrlist-table-body');
  4727. const empty = document.getElementById('addrlist-empty');
  4728. if (!tbody) return;
  4729. tbody.innerHTML = '';
  4730. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4731. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4732. // Update filter select
  4733. const sel = document.getElementById('addrlist-filter-name');
  4734. if (sel) {
  4735. const cur = sel.value;
  4736. sel.innerHTML = '<option value="">All Lists</option>';
  4737. const set = new Set((state.addressLists || []).map(a => a.name));
  4738. set.forEach(n => {
  4739. const opt = document.createElement('option');
  4740. opt.value = n;
  4741. opt.innerText = n;
  4742. if (n === cur) opt.selected = true;
  4743. sel.appendChild(opt);
  4744. });
  4745. }
  4746. if (entries.length === 0) {
  4747. empty?.classList.remove('hidden');
  4748. return;
  4749. }
  4750. empty?.classList.add('hidden');
  4751. entries.forEach((e, idx) => {
  4752. const tr = document.createElement('tr');
  4753. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4754. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4755. tr.innerHTML = `
  4756. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4757. <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>
  4758. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4759. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4760. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4761. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4762. <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>
  4763. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4764. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4765. </td>
  4766. `;
  4767. tbody.appendChild(tr);
  4768. });
  4769. populateCommonAddrListDatalist();
  4770. }
  4771. function openAddAddrListModal() {
  4772. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4773. document.getElementById('addrlist-modal-id').value = '';
  4774. document.getElementById('addrlist-modal-name').value = '';
  4775. document.getElementById('addrlist-modal-addr').value = '';
  4776. document.getElementById('addrlist-modal-comment').value = '';
  4777. document.getElementById('addrlist-modal-disabled').checked = false;
  4778. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4779. if (submitBtn) submitBtn.innerText = 'Add to List';
  4780. document.getElementById('addrlist-modal').classList.remove('hidden');
  4781. }
  4782. function openEditAddrListModal(id) {
  4783. const e = (state.addressLists || []).find(item => item.id === id);
  4784. if (!e) return;
  4785. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4786. document.getElementById('addrlist-modal-id').value = e.id;
  4787. document.getElementById('addrlist-modal-name').value = e.name;
  4788. document.getElementById('addrlist-modal-addr').value = e.address;
  4789. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4790. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4791. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4792. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4793. document.getElementById('addrlist-modal').classList.remove('hidden');
  4794. }
  4795. function closeAddrListModal() {
  4796. document.getElementById('addrlist-modal').classList.add('hidden');
  4797. }
  4798. async function submitSaveAddrList(e) {
  4799. e.preventDefault();
  4800. const id = document.getElementById('addrlist-modal-id').value;
  4801. const name = document.getElementById('addrlist-modal-name').value.trim();
  4802. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4803. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4804. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4805. try {
  4806. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4807. method: 'POST',
  4808. headers: { 'Content-Type': 'application/json' },
  4809. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4810. });
  4811. if (res.ok) {
  4812. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4813. closeAddrListModal();
  4814. loadFirewall(false);
  4815. } else {
  4816. const err = await res.json();
  4817. showToast('Error', err.message || 'Failed to save address list', 'error');
  4818. }
  4819. } catch (err) {
  4820. showToast('Error', err.message, 'error');
  4821. }
  4822. }
  4823. async function toggleAddrListState(id, disabled) {
  4824. try {
  4825. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4826. method: 'POST',
  4827. headers: { 'Content-Type': 'application/json' },
  4828. body: JSON.stringify({ disabled })
  4829. });
  4830. if (res.ok) {
  4831. loadFirewall(false);
  4832. }
  4833. } catch (err) {
  4834. showToast('Error', err.message, 'error');
  4835. }
  4836. }
  4837. async function deleteAddrList(id) {
  4838. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4839. try {
  4840. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4841. if (res.ok) {
  4842. showToast('Deleted', 'Address list item removed', 'info');
  4843. loadFirewall(false);
  4844. }
  4845. } catch (err) {
  4846. showToast('Error', err.message, 'error');
  4847. }
  4848. }
  4849. // ----------------- Geo-Location IP Management -----------------
  4850. async function loadGeoIP() {
  4851. try {
  4852. const [statusRes, countriesRes] = await Promise.all([
  4853. fetch(`${API_BASE}/firewall/geoip/status`),
  4854. fetch(`${API_BASE}/firewall/geoip/countries`)
  4855. ]);
  4856. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4857. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4858. updateGeoHeader();
  4859. renderGeoCountries();
  4860. } catch (err) {
  4861. console.error('Failed to load GeoIP:', err);
  4862. }
  4863. }
  4864. function getGeoUsageMap() {
  4865. const usage = {};
  4866. const checkRule = (r, type) => {
  4867. ['src_geoip', 'dst_geoip'].forEach(field => {
  4868. let val = (r && r[field]) || '';
  4869. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4870. if (code) {
  4871. if (!usage[code]) usage[code] = [];
  4872. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4873. if (!usage[code].includes(label)) usage[code].push(label);
  4874. }
  4875. });
  4876. };
  4877. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4878. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4879. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4880. return usage;
  4881. }
  4882. function updateGeoHeader() {
  4883. const s = state.geoStatus || {};
  4884. const statusBadge = document.getElementById('geo-status-badge');
  4885. if (statusBadge) {
  4886. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4887. statusBadge.className = s.auto_update
  4888. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4889. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4890. }
  4891. const intervalLabel = document.getElementById('geo-interval-label');
  4892. if (intervalLabel) {
  4893. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4894. }
  4895. const usageMap = getGeoUsageMap();
  4896. const inUseCount = Object.keys(usageMap).length;
  4897. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4898. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4899. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4900. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4901. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4902. if (lastSyncEl) {
  4903. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4904. const d = new Date(s.last_updated);
  4905. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4906. } else {
  4907. lastSyncEl.innerText = 'Never (Sync Pending)';
  4908. }
  4909. }
  4910. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4911. if (nextSyncEl) {
  4912. if (s.next_update && !s.next_update.startsWith('0001')) {
  4913. const d = new Date(s.next_update);
  4914. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4915. } else {
  4916. nextSyncEl.innerText = '-';
  4917. }
  4918. }
  4919. const badge = document.getElementById('fw-badge-geo');
  4920. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4921. }
  4922. function renderGeoCountries() {
  4923. const tbody = document.getElementById('geo-table-body');
  4924. const empty = document.getElementById('geo-empty');
  4925. if (!tbody) return;
  4926. tbody.innerHTML = '';
  4927. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4928. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4929. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4930. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4931. const usageMap = getGeoUsageMap();
  4932. const countries = (state.geoCountries || []).filter(c => {
  4933. const isUsed = !!usageMap[c.code];
  4934. if (inUseOnly && !isUsed) return false;
  4935. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4936. if (continent && c.continent !== continent) return false;
  4937. if (q) {
  4938. const matchCode = c.code.toLowerCase().includes(q);
  4939. const matchName = c.name.toLowerCase().includes(q);
  4940. if (!matchCode && !matchName) return false;
  4941. }
  4942. return true;
  4943. });
  4944. if (countries.length === 0) {
  4945. empty?.classList.remove('hidden');
  4946. return;
  4947. }
  4948. empty?.classList.add('hidden');
  4949. countries.forEach(c => {
  4950. const tr = document.createElement('tr');
  4951. const isUsed = !!usageMap[c.code];
  4952. const rulesUsing = usageMap[c.code] || [];
  4953. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4954. let statusHtml = '';
  4955. if (isUsed) {
  4956. 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>`;
  4957. } else if (c.subnet_count > 0) {
  4958. 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>';
  4959. } else {
  4960. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4961. }
  4962. tr.innerHTML = `
  4963. <td class="py-2.5 px-3 text-center">
  4964. <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'}">
  4965. ${c.code}
  4966. </span>
  4967. </td>
  4968. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4969. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4970. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4971. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4972. </td>
  4973. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4974. <td class="py-2.5 px-3">
  4975. ${statusHtml}
  4976. </td>
  4977. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4978. <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>
  4979. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4980. </td>
  4981. `;
  4982. tbody.appendChild(tr);
  4983. });
  4984. }
  4985. function quickFilterGeo(preset) {
  4986. const searchInput = document.getElementById('geo-search-input');
  4987. const continentSel = document.getElementById('geo-continent-filter');
  4988. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4989. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4990. if (searchInput) searchInput.value = '';
  4991. if (continentSel) continentSel.value = '';
  4992. if (inUseCheck) inUseCheck.checked = false;
  4993. if (cachedCheck) cachedCheck.checked = false;
  4994. if (preset === 'GR') {
  4995. if (searchInput) searchInput.value = 'Greece';
  4996. } else if (preset === 'Europe') {
  4997. if (continentSel) continentSel.value = 'Europe';
  4998. } else if (preset === 'HIGHRISK') {
  4999. if (searchInput) searchInput.value = 'China';
  5000. }
  5001. renderGeoCountries();
  5002. }
  5003. async function toggleGeoCountry(code, enabled) {
  5004. try {
  5005. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5006. method: 'POST',
  5007. headers: { 'Content-Type': 'application/json' },
  5008. body: JSON.stringify({ enabled })
  5009. });
  5010. if (res.ok) {
  5011. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5012. loadGeoIP();
  5013. } else {
  5014. const err = await res.json();
  5015. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5016. }
  5017. } catch (err) {
  5018. showToast('Error', err.message, 'error');
  5019. }
  5020. }
  5021. async function updateGeoCountry(code) {
  5022. try {
  5023. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5024. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5025. if (res.ok) {
  5026. const data = await res.json();
  5027. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5028. loadGeoIP();
  5029. } else {
  5030. const err = await res.json();
  5031. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5032. }
  5033. } catch (err) {
  5034. showToast('Error', err.message, 'error');
  5035. }
  5036. }
  5037. async function triggerGeoUpdateNow() {
  5038. const spinner = document.getElementById('geo-update-spinner');
  5039. if (spinner) spinner.classList.remove('hidden');
  5040. try {
  5041. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5042. if (res.ok) {
  5043. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5044. setTimeout(() => {
  5045. loadGeoIP();
  5046. if (spinner) spinner.classList.add('hidden');
  5047. }, 2500);
  5048. } else {
  5049. const err = await res.json();
  5050. showToast('Notice', err.message || 'Update in progress', 'info');
  5051. if (spinner) spinner.classList.add('hidden');
  5052. }
  5053. } catch (err) {
  5054. showToast('Error', err.message, 'error');
  5055. if (spinner) spinner.classList.add('hidden');
  5056. }
  5057. }
  5058. async function applyGeoPreset(preset) {
  5059. try {
  5060. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5061. method: 'POST',
  5062. headers: { 'Content-Type': 'application/json' },
  5063. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5064. });
  5065. if (res.ok) {
  5066. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5067. loadGeoIP();
  5068. }
  5069. } catch (err) {
  5070. showToast('Error', err.message, 'error');
  5071. }
  5072. }
  5073. function openGeoIntervalModal() {
  5074. const s = state.geoStatus || {};
  5075. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5076. const sel = document.getElementById('geo-cfg-interval');
  5077. const customBox = document.getElementById('geo-cfg-custom-box');
  5078. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5079. const curHours = s.interval_hours || 24;
  5080. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5081. if (matchOption) {
  5082. sel.value = String(curHours);
  5083. customBox.classList.add('hidden');
  5084. } else {
  5085. sel.value = 'custom';
  5086. customHoursInput.value = curHours;
  5087. customBox.classList.remove('hidden');
  5088. }
  5089. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5090. }
  5091. function closeGeoIntervalModal() {
  5092. document.getElementById('geo-interval-modal').classList.add('hidden');
  5093. }
  5094. function toggleCustomGeoInterval() {
  5095. const val = document.getElementById('geo-cfg-interval').value;
  5096. const customBox = document.getElementById('geo-cfg-custom-box');
  5097. if (val === 'custom') {
  5098. customBox.classList.remove('hidden');
  5099. } else {
  5100. customBox.classList.add('hidden');
  5101. }
  5102. }
  5103. async function submitGeoIntervalSettings(e) {
  5104. e.preventDefault();
  5105. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5106. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5107. let hours = 24;
  5108. if (intervalVal === 'custom') {
  5109. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5110. } else {
  5111. hours = parseInt(intervalVal, 10) || 24;
  5112. }
  5113. try {
  5114. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5115. method: 'POST',
  5116. headers: { 'Content-Type': 'application/json' },
  5117. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5118. });
  5119. if (res.ok) {
  5120. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5121. closeGeoIntervalModal();
  5122. loadGeoIP();
  5123. } else {
  5124. const err = await res.json();
  5125. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5126. }
  5127. } catch (err) {
  5128. showToast('Error', err.message, 'error');
  5129. }
  5130. }
  5131. async function viewGeoSubnets(code, name) {
  5132. if (!name) {
  5133. const found = (state.geoCountries || []).find(x => x.code === code);
  5134. name = found ? found.name : code;
  5135. }
  5136. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5137. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5138. const listEl = document.getElementById('geo-subnets-list');
  5139. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5140. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5141. try {
  5142. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5143. if (res.ok) {
  5144. const data = await res.json();
  5145. const subnets = data.subnets || [];
  5146. if (subnets.length === 0) {
  5147. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5148. } else {
  5149. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5150. }
  5151. } else {
  5152. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5153. }
  5154. } catch (err) {
  5155. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5156. }
  5157. }
  5158. function closeGeoSubnetsModal() {
  5159. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5160. }
  5161. // ----------------- Active Connections Tracking -----------------
  5162. async function loadConnections() {
  5163. try {
  5164. const res = await fetch(`${API_BASE}/firewall/connections`);
  5165. const data = await res.json();
  5166. state.connections = Array.isArray(data) ? data : [];
  5167. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5168. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5169. renderConnections();
  5170. } catch (err) {
  5171. console.error('Failed to load connections:', err);
  5172. }
  5173. }
  5174. function renderConnections() {
  5175. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5176. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5177. const tbody = document.getElementById('conns-table-body');
  5178. const empty = document.getElementById('conns-empty');
  5179. if (!tbody) return;
  5180. tbody.innerHTML = '';
  5181. const conns = (state.connections || []).filter(c => {
  5182. if (protoFilter && c.protocol !== protoFilter) return false;
  5183. if (search) {
  5184. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5185. if (!line.includes(search)) return false;
  5186. }
  5187. return true;
  5188. });
  5189. if (conns.length === 0) {
  5190. empty?.classList.remove('hidden');
  5191. return;
  5192. }
  5193. empty?.classList.add('hidden');
  5194. conns.slice(0, 150).forEach(c => {
  5195. const tr = document.createElement('tr');
  5196. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5197. let stateColor = 'text-slate-400';
  5198. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5199. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5200. tr.innerHTML = `
  5201. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5202. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5203. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5204. <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>
  5205. <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>
  5206. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5207. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5208. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5209. <td class="py-2.5 px-3 text-right font-sans">
  5210. <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>
  5211. </td>
  5212. `;
  5213. tbody.appendChild(tr);
  5214. });
  5215. }
  5216. async function killConnection(protocol, src, sport, dst, dport) {
  5217. try {
  5218. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5219. method: 'POST',
  5220. headers: { 'Content-Type': 'application/json' },
  5221. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5222. });
  5223. if (res.ok) {
  5224. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5225. loadConnections();
  5226. }
  5227. } catch (err) {
  5228. showToast('Error', err.message, 'error');
  5229. }
  5230. }
  5231. async function resetFirewallCounters() {
  5232. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5233. try {
  5234. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5235. if (res.ok) {
  5236. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5237. loadFirewall(false);
  5238. }
  5239. } catch (err) {
  5240. showToast('Error', err.message, 'error');
  5241. }
  5242. }
  5243. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5244. function switchRoutesSubTab(tab) {
  5245. state.routesSubTab = tab;
  5246. const tabs = ['routes', 'rules', 'tables'];
  5247. tabs.forEach(t => {
  5248. const panel = document.getElementById(`routes-subtab-${t}`);
  5249. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5250. if (panel) {
  5251. if (t === tab) panel.classList.remove('hidden');
  5252. else panel.classList.add('hidden');
  5253. }
  5254. if (btn) {
  5255. if (t === tab) {
  5256. 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';
  5257. } else {
  5258. 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';
  5259. }
  5260. }
  5261. });
  5262. setTimeout(initTableSorting, 50);
  5263. }
  5264. async function loadRoutes() {
  5265. try {
  5266. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5267. fetch(`${API_BASE}/routes`),
  5268. fetch(`${API_BASE}/routing/rules`),
  5269. fetch(`${API_BASE}/routing/tables`)
  5270. ]);
  5271. if (routesRes.ok) state.routes = await routesRes.json();
  5272. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5273. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5274. const bRoutes = document.getElementById('routes-badge-routes');
  5275. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5276. const showSystem = document.getElementById('prule-show-system')?.checked;
  5277. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5278. const bRules = document.getElementById('routes-badge-rules');
  5279. if (bRules) bRules.innerText = userRules.length;
  5280. const bTables = document.getElementById('routes-badge-tables');
  5281. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5282. const bRoutesCount = document.getElementById('badge-routes-count');
  5283. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5284. renderRoutesList();
  5285. renderPolicyRules();
  5286. renderRoutingTables();
  5287. } catch (err) {
  5288. console.error('Failed to load routing:', err);
  5289. }
  5290. }
  5291. function renderRoutesList() {
  5292. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5293. const tbody = document.getElementById('routes-table-body');
  5294. const empty = document.getElementById('routes-empty');
  5295. if (!tbody) return;
  5296. tbody.innerHTML = '';
  5297. // Update table filter select
  5298. const sel = document.getElementById('routes-filter-table');
  5299. if (sel) {
  5300. const cur = sel.value;
  5301. sel.innerHTML = '<option value="">All Tables</option>';
  5302. (state.routingTables || []).forEach(t => {
  5303. const opt = document.createElement('option');
  5304. opt.value = t.name;
  5305. opt.innerText = t.name;
  5306. if (t.name === cur) opt.selected = true;
  5307. sel.appendChild(opt);
  5308. });
  5309. }
  5310. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5311. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5312. if (routes.length === 0) {
  5313. empty?.classList.remove('hidden');
  5314. return;
  5315. }
  5316. empty?.classList.add('hidden');
  5317. routes.forEach(r => {
  5318. const tr = document.createElement('tr');
  5319. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5320. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5321. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5322. let flags = '';
  5323. if (r.dynamic) flags += 'D';
  5324. if (r.active) flags += 'A';
  5325. if (r.connect) flags += 'C';
  5326. if (r.static) flags += 'S';
  5327. if (r.disabled) flags += 'X';
  5328. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5329. tr.innerHTML = `
  5330. <td class="py-2.5 px-3 text-center">
  5331. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${r.active ? 'text-cyan-400 border border-cyan-800/40' : 'text-slate-500'}">
  5332. ${flags || '-'}
  5333. </span>
  5334. </td>
  5335. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5336. <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>
  5337. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5338. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5339. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5340. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5341. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5342. ${r.static ? `
  5343. <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>
  5344. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5345. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5346. ` : `
  5347. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5348. `}
  5349. </td>
  5350. `;
  5351. tbody.appendChild(tr);
  5352. });
  5353. }
  5354. function openAddRouteModal() {
  5355. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5356. document.getElementById('route-modal-id').value = '';
  5357. document.getElementById('route-modal-old-dst').value = '';
  5358. document.getElementById('route-modal-old-gw').value = '';
  5359. document.getElementById('route-modal-old-distance').value = '';
  5360. document.getElementById('route-modal-old-table').value = '';
  5361. document.getElementById('route-modal-old-iface').value = '';
  5362. const dstInput = document.getElementById('route-modal-dst');
  5363. const gwInput = document.getElementById('route-modal-gw');
  5364. const distInput = document.getElementById('route-modal-distance');
  5365. const ifaceSelect = document.getElementById('route-modal-iface');
  5366. const tableSelect = document.getElementById('route-modal-table');
  5367. const commentInput = document.getElementById('route-modal-comment');
  5368. const disCheck = document.getElementById('route-modal-disabled');
  5369. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5370. dstInput.disabled = false;
  5371. dstInput.value = '0.0.0.0/0';
  5372. gwInput.disabled = false;
  5373. gwInput.value = '';
  5374. distInput.disabled = false;
  5375. distInput.value = '1';
  5376. ifaceSelect.disabled = false;
  5377. tableSelect.disabled = false;
  5378. commentInput.disabled = false;
  5379. commentInput.value = '';
  5380. disCheck.disabled = false;
  5381. disCheck.checked = false;
  5382. if (saveBtn) saveBtn.classList.remove('hidden');
  5383. populateInterfaceSelect('route-modal-iface');
  5384. // Populate tables
  5385. tableSelect.innerHTML = '';
  5386. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5387. const opt = document.createElement('option');
  5388. opt.value = t.name;
  5389. opt.innerText = t.name;
  5390. if (t.name === 'main') opt.selected = true;
  5391. tableSelect.appendChild(opt);
  5392. });
  5393. document.getElementById('route-modal').classList.remove('hidden');
  5394. }
  5395. function openEditRouteModal(id) {
  5396. const r = (state.routes || []).find(route => route.id === id);
  5397. if (!r) return;
  5398. const isStatic = !!r.static;
  5399. document.getElementById('route-modal-title').innerText = isStatic
  5400. ? `Edit Route: ${r.dst_address}`
  5401. : `Route Properties (Read Only): ${r.dst_address}`;
  5402. document.getElementById('route-modal-id').value = r.id;
  5403. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5404. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5405. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5406. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5407. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5408. const dstInput = document.getElementById('route-modal-dst');
  5409. const gwInput = document.getElementById('route-modal-gw');
  5410. const distInput = document.getElementById('route-modal-distance');
  5411. const ifaceSelect = document.getElementById('route-modal-iface');
  5412. const tableSelect = document.getElementById('route-modal-table');
  5413. const commentInput = document.getElementById('route-modal-comment');
  5414. const disCheck = document.getElementById('route-modal-disabled');
  5415. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5416. dstInput.value = r.dst_address;
  5417. gwInput.value = r.gateway || '';
  5418. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5419. commentInput.value = r.comment || '';
  5420. disCheck.checked = !!r.disabled;
  5421. dstInput.disabled = !isStatic;
  5422. gwInput.disabled = !isStatic;
  5423. distInput.disabled = !isStatic;
  5424. ifaceSelect.disabled = !isStatic;
  5425. tableSelect.disabled = !isStatic;
  5426. commentInput.disabled = !isStatic;
  5427. disCheck.disabled = !isStatic;
  5428. if (saveBtn) {
  5429. if (isStatic) {
  5430. saveBtn.classList.remove('hidden');
  5431. } else {
  5432. saveBtn.classList.add('hidden');
  5433. }
  5434. }
  5435. populateInterfaceSelect('route-modal-iface', r.interface);
  5436. tableSelect.innerHTML = '';
  5437. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5438. const opt = document.createElement('option');
  5439. opt.value = t.name;
  5440. opt.innerText = t.name;
  5441. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5442. tableSelect.appendChild(opt);
  5443. });
  5444. document.getElementById('route-modal').classList.remove('hidden');
  5445. }
  5446. function closeRouteModal() {
  5447. document.getElementById('route-modal').classList.add('hidden');
  5448. }
  5449. async function submitSaveRoute(e) {
  5450. e.preventDefault();
  5451. const id = document.getElementById('route-modal-id').value;
  5452. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5453. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5454. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5455. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5456. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5457. const dst = document.getElementById('route-modal-dst').value.trim();
  5458. const gw = document.getElementById('route-modal-gw').value.trim();
  5459. const table = document.getElementById('route-modal-table').value;
  5460. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5461. const iface = document.getElementById('route-modal-iface').value;
  5462. const comment = document.getElementById('route-modal-comment').value.trim();
  5463. const disabled = document.getElementById('route-modal-disabled').checked;
  5464. if (!dst) {
  5465. showToast('Error', 'Destination address is required', 'error');
  5466. return;
  5467. }
  5468. if (!gw && !iface) {
  5469. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5470. return;
  5471. }
  5472. const payload = {
  5473. id,
  5474. old_dst_address: oldDst,
  5475. old_gateway: oldGw,
  5476. old_routing_table: oldTable,
  5477. old_interface: oldIface,
  5478. dst_address: dst,
  5479. gateway: gw || iface,
  5480. routing_table: table,
  5481. distance,
  5482. interface: iface,
  5483. comment,
  5484. disabled
  5485. };
  5486. if (oldDistStr !== undefined && oldDistStr !== '') {
  5487. payload.old_distance = parseInt(oldDistStr, 10);
  5488. }
  5489. try {
  5490. const res = await fetch(`${API_BASE}/routes`, {
  5491. method: 'POST',
  5492. headers: { 'Content-Type': 'application/json' },
  5493. body: JSON.stringify(payload)
  5494. });
  5495. if (res.ok) {
  5496. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5497. closeRouteModal();
  5498. loadRoutes();
  5499. } else {
  5500. const err = await res.json();
  5501. showToast('Error', err.message || 'Failed to save route', 'error');
  5502. }
  5503. } catch (err) {
  5504. showToast('Error', err.message, 'error');
  5505. }
  5506. }
  5507. async function toggleRouteState(id, disabled) {
  5508. try {
  5509. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5510. method: 'POST',
  5511. headers: { 'Content-Type': 'application/json' },
  5512. body: JSON.stringify({ disabled })
  5513. });
  5514. if (res.ok) loadRoutes();
  5515. } catch (err) {
  5516. showToast('Error', err.message, 'error');
  5517. }
  5518. }
  5519. async function deleteRoute(id) {
  5520. if (!confirm('Are you sure you want to delete this route?')) return;
  5521. try {
  5522. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5523. if (res.ok) {
  5524. showToast('Deleted', 'Route removed', 'success');
  5525. loadRoutes();
  5526. }
  5527. } catch (err) {
  5528. showToast('Error', err.message, 'error');
  5529. }
  5530. }
  5531. // ----------------- Policy Rules (/ip route rule) -----------------
  5532. function renderPolicyRules() {
  5533. const tbody = document.getElementById('rules-table-body');
  5534. const empty = document.getElementById('rules-empty');
  5535. if (!tbody) return;
  5536. tbody.innerHTML = '';
  5537. const showSystem = document.getElementById('prule-show-system')?.checked;
  5538. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5539. const countBadge = document.getElementById('rules-count-badge');
  5540. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5541. const bRules = document.getElementById('routes-badge-rules');
  5542. if (bRules) bRules.innerText = filtered.length;
  5543. if (filtered.length === 0) {
  5544. empty?.classList.remove('hidden');
  5545. return;
  5546. }
  5547. empty?.classList.add('hidden');
  5548. filtered.forEach(pr => {
  5549. const isSys = pr.is_default || pr.is_system;
  5550. const tr = document.createElement('tr');
  5551. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5552. tr.innerHTML = `
  5553. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5554. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5555. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5556. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5557. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5558. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5559. <td class="py-2.5 px-3 text-right font-sans">
  5560. ${!pr.is_default ? `
  5561. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5562. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5563. </td>
  5564. `;
  5565. tbody.appendChild(tr);
  5566. });
  5567. }
  5568. function openAddPolicyRuleModal() {
  5569. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5570. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5571. document.getElementById('prule-modal-mark').value = '';
  5572. document.getElementById('prule-modal-src').value = '';
  5573. document.getElementById('prule-modal-dst').value = '';
  5574. const sel = document.getElementById('prule-modal-table');
  5575. sel.innerHTML = '';
  5576. (state.routingTables || []).forEach(t => {
  5577. const opt = document.createElement('option');
  5578. opt.value = t.name;
  5579. opt.innerText = t.name;
  5580. sel.appendChild(opt);
  5581. });
  5582. document.getElementById('prule-modal').classList.remove('hidden');
  5583. }
  5584. function closePolicyRuleModal() {
  5585. document.getElementById('prule-modal').classList.add('hidden');
  5586. }
  5587. async function submitSavePolicyRule(e) {
  5588. e.preventDefault();
  5589. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5590. const mark = document.getElementById('prule-modal-mark').value.trim();
  5591. const src = document.getElementById('prule-modal-src').value.trim();
  5592. const dst = document.getElementById('prule-modal-dst').value.trim();
  5593. const table = document.getElementById('prule-modal-table').value;
  5594. const action = document.getElementById('prule-modal-action').value;
  5595. try {
  5596. const res = await fetch(`${API_BASE}/routing/rules`, {
  5597. method: 'POST',
  5598. headers: { 'Content-Type': 'application/json' },
  5599. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5600. });
  5601. if (res.ok) {
  5602. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5603. closePolicyRuleModal();
  5604. loadRoutes();
  5605. } else {
  5606. const err = await res.json();
  5607. showToast('Error', err.message, 'error');
  5608. }
  5609. } catch (err) {
  5610. showToast('Error', err.message, 'error');
  5611. }
  5612. }
  5613. async function deletePolicyRule(id) {
  5614. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5615. try {
  5616. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5617. if (res.ok) {
  5618. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5619. loadRoutes();
  5620. }
  5621. } catch (err) {
  5622. showToast('Error', err.message, 'error');
  5623. }
  5624. }
  5625. // ----------------- Routing Tables -----------------
  5626. function renderRoutingTables() {
  5627. const tbody = document.getElementById('tables-table-body');
  5628. if (!tbody) return;
  5629. tbody.innerHTML = '';
  5630. (state.routingTables || []).forEach(t => {
  5631. const tr = document.createElement('tr');
  5632. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5633. tr.innerHTML = `
  5634. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5635. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5636. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5637. `;
  5638. tbody.appendChild(tr);
  5639. });
  5640. }
  5641. function openAddTableModal() {
  5642. document.getElementById('table-modal-name').value = '';
  5643. document.getElementById('table-modal-id').value = '';
  5644. document.getElementById('table-modal-comment').value = '';
  5645. document.getElementById('table-modal').classList.remove('hidden');
  5646. }
  5647. function closeTableModal() {
  5648. document.getElementById('table-modal').classList.add('hidden');
  5649. }
  5650. async function submitSaveTable(e) {
  5651. e.preventDefault();
  5652. const name = document.getElementById('table-modal-name').value.trim();
  5653. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5654. const comment = document.getElementById('table-modal-comment').value.trim();
  5655. try {
  5656. const res = await fetch(`${API_BASE}/routing/tables`, {
  5657. method: 'POST',
  5658. headers: { 'Content-Type': 'application/json' },
  5659. body: JSON.stringify({ name, table_id: id, comment })
  5660. });
  5661. if (res.ok) {
  5662. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5663. closeTableModal();
  5664. loadRoutes();
  5665. } else {
  5666. const err = await res.json();
  5667. showToast('Error', err.message, 'error');
  5668. }
  5669. } catch (err) {
  5670. showToast('Error', err.message, 'error');
  5671. }
  5672. }
  5673. async function loadDebianConfig() {
  5674. const view = document.getElementById('debian-config-view');
  5675. view.innerText = 'Generating live configuration...';
  5676. try {
  5677. const res = await fetch(`${API_BASE}/debian/config`);
  5678. const data = await res.json();
  5679. view.innerText = data.content || '# Empty config';
  5680. } catch (err) {
  5681. view.innerText = 'Failed to generate Debian network config.';
  5682. }
  5683. }
  5684. async function saveDebianConfig() {
  5685. try {
  5686. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5687. const data = await res.json();
  5688. if (res.ok) {
  5689. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5690. loadDebianConfig();
  5691. }
  5692. } catch (err) {
  5693. showToast('Error', err.message, 'error');
  5694. }
  5695. }
  5696. function showToast(title, message, type = 'info') {
  5697. const container = document.getElementById('toast-container');
  5698. const toast = document.createElement('div');
  5699. const borderColors = {
  5700. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5701. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5702. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5703. };
  5704. 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}`;
  5705. toast.innerHTML = `
  5706. <div class="flex-1">
  5707. <div class="font-bold text-xs text-white">${title}</div>
  5708. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5709. </div>
  5710. `;
  5711. container.appendChild(toast);
  5712. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5713. setTimeout(() => {
  5714. toast.classList.add('opacity-0', 'translate-y-2');
  5715. setTimeout(() => toast.remove(), 300);
  5716. }, 4000);
  5717. }
  5718. function formatTraffic(bytesPerSec) {
  5719. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5720. const kb = bytesPerSec / 1024;
  5721. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5722. const mb = kb / 1024;
  5723. return `${mb.toFixed(2)} MB/s`;
  5724. }
  5725. function toggleSidebar() {
  5726. const sb = document.getElementById('sidebar');
  5727. sb.classList.toggle('-translate-x-full');
  5728. }
  5729. // ======================== EoIP (Ethernet over IP) ========================
  5730. async function loadEoIP(populate = true) {
  5731. try {
  5732. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5733. const data = await res.json();
  5734. state.eoipTunnels = Array.isArray(data) ? data : [];
  5735. const badge = document.getElementById('eoip-count-badge');
  5736. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5737. const sideBadge = document.getElementById('badge-eoip-count');
  5738. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5739. renderEoIPTunnels();
  5740. } catch (err) {
  5741. console.error('Failed to load EoIP:', err);
  5742. }
  5743. }
  5744. function renderEoIPTunnels() {
  5745. const tbody = document.getElementById('eoip-table-body');
  5746. const empty = document.getElementById('eoip-empty');
  5747. if (!tbody) return;
  5748. tbody.innerHTML = '';
  5749. const tunnels = state.eoipTunnels || [];
  5750. if (tunnels.length === 0) {
  5751. empty?.classList.remove('hidden');
  5752. return;
  5753. }
  5754. empty?.classList.add('hidden');
  5755. tunnels.forEach(t => {
  5756. const tr = document.createElement('tr');
  5757. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5758. tr.innerHTML = `
  5759. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5760. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5761. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5762. <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>
  5763. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5764. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5765. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5766. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5767. <td class="py-2.5 px-3 font-mono text-[11px]">
  5768. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5769. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5770. </td>
  5771. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5772. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5773. <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>
  5774. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5775. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5776. </td>
  5777. `;
  5778. tbody.appendChild(tr);
  5779. });
  5780. }
  5781. function openAddEoIPModal() {
  5782. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5783. document.getElementById('eoip-modal-id').value = '';
  5784. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5785. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5786. document.getElementById('eoip-modal-remote').value = '';
  5787. document.getElementById('eoip-modal-ip').value = '';
  5788. document.getElementById('eoip-modal-local').value = '';
  5789. document.getElementById('eoip-modal-mac').value = '';
  5790. document.getElementById('eoip-modal-mtu').value = '1500';
  5791. document.getElementById('eoip-modal-comment').value = '';
  5792. document.getElementById('eoip-modal-clampmss').checked = true;
  5793. document.getElementById('eoip-modal-disabled').checked = false;
  5794. document.getElementById('eoip-modal').classList.remove('hidden');
  5795. }
  5796. function openEditEoIPModal(id) {
  5797. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5798. if (!t) return;
  5799. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5800. document.getElementById('eoip-modal-id').value = t.id;
  5801. document.getElementById('eoip-modal-name').value = t.name;
  5802. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5803. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5804. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5805. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5806. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5807. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5808. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5809. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5810. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5811. document.getElementById('eoip-modal').classList.remove('hidden');
  5812. }
  5813. function closeEoIPModal() {
  5814. document.getElementById('eoip-modal').classList.add('hidden');
  5815. }
  5816. async function submitSaveEoIP(e) {
  5817. e.preventDefault();
  5818. const id = document.getElementById('eoip-modal-id').value;
  5819. const name = document.getElementById('eoip-modal-name').value.trim();
  5820. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5821. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5822. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5823. const local = document.getElementById('eoip-modal-local').value.trim();
  5824. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5825. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5826. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5827. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5828. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5829. try {
  5830. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5831. method: 'POST',
  5832. headers: { 'Content-Type': 'application/json' },
  5833. body: JSON.stringify({
  5834. id,
  5835. name,
  5836. tunnel_id: tunnelId,
  5837. remote_address: remote,
  5838. ip_address: ipAddress,
  5839. local_address: local,
  5840. mac_address: mac,
  5841. mtu,
  5842. clamp_mss: clampMss,
  5843. comment,
  5844. disabled
  5845. })
  5846. });
  5847. if (res.ok) {
  5848. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5849. closeEoIPModal();
  5850. loadEoIP(false);
  5851. fetchData(false);
  5852. } else {
  5853. const err = await res.json();
  5854. showToast('Error', err.message, 'error');
  5855. }
  5856. } catch (err) {
  5857. showToast('Error', err.message, 'error');
  5858. }
  5859. }
  5860. async function toggleEoIPState(id, disabled) {
  5861. try {
  5862. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5863. method: 'POST',
  5864. headers: { 'Content-Type': 'application/json' },
  5865. body: JSON.stringify({ disabled })
  5866. });
  5867. if (res.ok) {
  5868. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5869. loadEoIP(false);
  5870. fetchData(false);
  5871. }
  5872. } catch (err) {
  5873. showToast('Error', err.message, 'error');
  5874. }
  5875. }
  5876. async function deleteEoIP(id) {
  5877. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5878. try {
  5879. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5880. if (res.ok) {
  5881. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5882. loadEoIP(false);
  5883. fetchData(false);
  5884. }
  5885. } catch (err) {
  5886. showToast('Error', err.message, 'error');
  5887. }
  5888. }
  5889. // ======================== PPP Central Hub & Servers ========================
  5890. function switchPPPSubTab(tab) {
  5891. state.pppSubTab = tab;
  5892. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5893. tabs.forEach(t => {
  5894. const panel = document.getElementById(`ppp-subtab-${t}`);
  5895. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5896. if (panel) {
  5897. if (t === tab) panel.classList.remove('hidden');
  5898. else panel.classList.add('hidden');
  5899. }
  5900. if (btn) {
  5901. if (t === tab) {
  5902. 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';
  5903. } else {
  5904. 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';
  5905. }
  5906. }
  5907. });
  5908. const addBtn = document.getElementById('ppp-primary-add-btn');
  5909. if (addBtn) {
  5910. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5911. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5912. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5913. else addBtn.innerHTML = '<span>Save Config</span>';
  5914. }
  5915. if (tab === 'active') loadPPPSessions();
  5916. }
  5917. function openCurrentPPPModal() {
  5918. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5919. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5920. else if (state.pppSubTab === 'active') loadPPPSessions();
  5921. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5922. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5923. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5924. }
  5925. async function loadPPP(populateDropdowns = true) {
  5926. await Promise.all([
  5927. loadPPPSecrets(),
  5928. loadPPPProfiles(),
  5929. loadPPPServers(),
  5930. loadPPPSessions()
  5931. ]);
  5932. }
  5933. async function loadPPPSecrets() {
  5934. try {
  5935. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5936. const data = await res.json();
  5937. state.pppSecrets = Array.isArray(data) ? data : [];
  5938. const b = document.getElementById('ppp-badge-secrets');
  5939. if (b) b.innerText = state.pppSecrets.length;
  5940. const b2 = document.getElementById('secrets-count-badge');
  5941. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5942. renderPPPSecrets();
  5943. } catch (err) {
  5944. console.error('Failed to load PPP secrets:', err);
  5945. }
  5946. }
  5947. function renderPPPSecrets() {
  5948. const tbody = document.getElementById('secrets-table-body');
  5949. const empty = document.getElementById('secrets-empty');
  5950. if (!tbody) return;
  5951. tbody.innerHTML = '';
  5952. const secrets = state.pppSecrets || [];
  5953. if (secrets.length === 0) {
  5954. empty?.classList.remove('hidden');
  5955. return;
  5956. }
  5957. empty?.classList.add('hidden');
  5958. secrets.forEach(s => {
  5959. const tr = document.createElement('tr');
  5960. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5961. tr.innerHTML = `
  5962. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5963. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5964. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5965. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5966. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5967. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5968. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5969. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5970. <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>
  5971. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5972. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5973. </td>
  5974. `;
  5975. tbody.appendChild(tr);
  5976. });
  5977. }
  5978. async function loadPPPProfiles() {
  5979. try {
  5980. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5981. const data = await res.json();
  5982. state.pppProfiles = Array.isArray(data) ? data : [];
  5983. const b = document.getElementById('ppp-badge-profiles');
  5984. if (b) b.innerText = state.pppProfiles.length;
  5985. const b2 = document.getElementById('profiles-count-badge');
  5986. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5987. // Populate profile selects across modals
  5988. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5989. selects.forEach(sid => {
  5990. const el = document.getElementById(sid);
  5991. if (!el) return;
  5992. const cur = el.value;
  5993. el.innerHTML = '';
  5994. state.pppProfiles.forEach(p => {
  5995. const opt = document.createElement('option');
  5996. opt.value = p.name;
  5997. opt.innerText = `${p.name} (${p.remote_address})`;
  5998. if (p.name === cur) opt.selected = true;
  5999. el.appendChild(opt);
  6000. });
  6001. });
  6002. renderPPPProfiles();
  6003. } catch (err) {
  6004. console.error('Failed to load PPP profiles:', err);
  6005. }
  6006. }
  6007. function renderPPPProfiles() {
  6008. const tbody = document.getElementById('profiles-table-body');
  6009. if (!tbody) return;
  6010. tbody.innerHTML = '';
  6011. (state.pppProfiles || []).forEach(p => {
  6012. const isDefault = p.name.startsWith('default');
  6013. const tr = document.createElement('tr');
  6014. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6015. tr.innerHTML = `
  6016. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6017. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6018. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6019. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6020. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6021. <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>
  6022. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6023. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6024. ${!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>`}
  6025. </td>
  6026. `;
  6027. tbody.appendChild(tr);
  6028. });
  6029. }
  6030. async function loadPPPServers() {
  6031. try {
  6032. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6033. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6034. fetch(`${API_BASE}/vpn/servers/pptp`),
  6035. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6036. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6037. ]);
  6038. if (pppoeRes.ok) {
  6039. state.pppoeServer = await pppoeRes.json();
  6040. const s = state.pppoeServer;
  6041. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6042. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6043. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6044. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6045. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6046. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6047. const pill = document.getElementById('pppoe-server-status-pill');
  6048. if (pill) {
  6049. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6050. 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';
  6051. }
  6052. setDotBadge('ppp-badge-pppoe-state', s.running);
  6053. }
  6054. if (pptpRes.ok) {
  6055. state.pptpServer = await pptpRes.json();
  6056. const s = state.pptpServer;
  6057. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6058. document.getElementById('pptp-server-port').value = s.port || 1723;
  6059. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6060. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6061. const pill = document.getElementById('pptp-server-status-pill');
  6062. if (pill) {
  6063. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6064. 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';
  6065. }
  6066. setDotBadge('ppp-badge-pptp-state', s.running);
  6067. }
  6068. if (l2tpRes.ok) {
  6069. state.l2tpServer = await l2tpRes.json();
  6070. const s = state.l2tpServer;
  6071. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6072. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6073. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6074. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6075. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6076. const pill = document.getElementById('l2tp-server-status-pill');
  6077. if (pill) {
  6078. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6079. 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';
  6080. }
  6081. setDotBadge('ppp-badge-l2tp-state', s.running);
  6082. }
  6083. if (ipsecRes.ok) {
  6084. state.ipsecServer = await ipsecRes.json();
  6085. const s = state.ipsecServer;
  6086. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6087. if (modalEn) modalEn.checked = !!s.enabled;
  6088. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6089. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6090. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6091. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6092. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6093. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6094. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6095. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6096. const pill = document.getElementById('modal-ipsec-server-status');
  6097. if (pill) {
  6098. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6099. 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';
  6100. }
  6101. }
  6102. } catch (err) {
  6103. console.error('Failed to load VPN servers:', err);
  6104. }
  6105. }
  6106. async function loadPPPSessions() {
  6107. try {
  6108. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6109. const data = await res.json();
  6110. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6111. const b = document.getElementById('ppp-badge-active');
  6112. if (b) b.innerText = state.pppActiveSessions.length;
  6113. const sideB = document.getElementById('badge-ppp-sessions');
  6114. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6115. renderPPPSessions();
  6116. } catch (err) {
  6117. console.error('Failed to load active PPP sessions:', err);
  6118. }
  6119. }
  6120. function renderPPPSessions() {
  6121. const tbody = document.getElementById('active-ppp-table-body');
  6122. const empty = document.getElementById('active-ppp-empty');
  6123. if (!tbody) return;
  6124. tbody.innerHTML = '';
  6125. const list = state.pppActiveSessions || [];
  6126. if (list.length === 0) {
  6127. empty?.classList.remove('hidden');
  6128. return;
  6129. }
  6130. empty?.classList.add('hidden');
  6131. list.forEach(s => {
  6132. const tr = document.createElement('tr');
  6133. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6134. tr.innerHTML = `
  6135. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6136. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6137. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6138. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6139. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6140. <td class="py-2.5 px-3 text-[11px]">
  6141. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6142. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6143. </td>
  6144. <td class="py-2.5 px-3 text-right font-sans">
  6145. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6146. </td>
  6147. `;
  6148. tbody.appendChild(tr);
  6149. });
  6150. }
  6151. async function disconnectPPPSession(iface) {
  6152. if (!confirm(`Disconnect session ${iface}?`)) return;
  6153. try {
  6154. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6155. if (res.ok) {
  6156. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6157. loadPPPSessions();
  6158. }
  6159. } catch (err) {
  6160. showToast('Error', err.message, 'error');
  6161. }
  6162. }
  6163. // PPP Secret Modal handlers
  6164. function openAddPPPSecretModal() {
  6165. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6166. document.getElementById('secret-modal-id').value = '';
  6167. document.getElementById('secret-modal-name').value = '';
  6168. document.getElementById('secret-modal-password').value = '';
  6169. document.getElementById('secret-modal-service').value = 'any';
  6170. document.getElementById('secret-modal-profile').value = 'default';
  6171. document.getElementById('secret-modal-local').value = '';
  6172. document.getElementById('secret-modal-remote').value = '';
  6173. document.getElementById('secret-modal-comment').value = '';
  6174. document.getElementById('secret-modal-disabled').checked = false;
  6175. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6176. }
  6177. function openEditPPPSecretModal(id) {
  6178. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6179. if (!s) return;
  6180. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6181. document.getElementById('secret-modal-id').value = s.id;
  6182. document.getElementById('secret-modal-name').value = s.name;
  6183. document.getElementById('secret-modal-password').value = s.password;
  6184. document.getElementById('secret-modal-service').value = s.service || 'any';
  6185. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6186. document.getElementById('secret-modal-local').value = s.local_address || '';
  6187. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6188. document.getElementById('secret-modal-comment').value = s.comment || '';
  6189. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6190. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6191. }
  6192. function closePPPSecretModal() {
  6193. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6194. }
  6195. async function submitSavePPPSecret(e) {
  6196. e.preventDefault();
  6197. const id = document.getElementById('secret-modal-id').value;
  6198. const name = document.getElementById('secret-modal-name').value.trim();
  6199. const password = document.getElementById('secret-modal-password').value.trim();
  6200. const service = document.getElementById('secret-modal-service').value;
  6201. const profile = document.getElementById('secret-modal-profile').value;
  6202. const local = document.getElementById('secret-modal-local').value.trim();
  6203. const remote = document.getElementById('secret-modal-remote').value.trim();
  6204. const comment = document.getElementById('secret-modal-comment').value.trim();
  6205. const disabled = document.getElementById('secret-modal-disabled').checked;
  6206. try {
  6207. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6208. method: 'POST',
  6209. headers: { 'Content-Type': 'application/json' },
  6210. body: JSON.stringify({
  6211. id,
  6212. name,
  6213. password,
  6214. service,
  6215. profile,
  6216. local_address: local,
  6217. remote_address: remote,
  6218. comment,
  6219. disabled
  6220. })
  6221. });
  6222. if (res.ok) {
  6223. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6224. closePPPSecretModal();
  6225. loadPPPSecrets();
  6226. } else {
  6227. const err = await res.json();
  6228. showToast('Error', err.message, 'error');
  6229. }
  6230. } catch (err) {
  6231. showToast('Error', err.message, 'error');
  6232. }
  6233. }
  6234. async function togglePPPSecretState(id, disabled) {
  6235. try {
  6236. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6237. method: 'POST',
  6238. headers: { 'Content-Type': 'application/json' },
  6239. body: JSON.stringify({ disabled })
  6240. });
  6241. if (res.ok) {
  6242. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6243. loadPPPSecrets();
  6244. }
  6245. } catch (err) {
  6246. showToast('Error', err.message, 'error');
  6247. }
  6248. }
  6249. async function deletePPPSecret(id) {
  6250. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6251. try {
  6252. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6253. if (res.ok) {
  6254. showToast('Deleted', 'Secret account removed', 'success');
  6255. loadPPPSecrets();
  6256. }
  6257. } catch (err) {
  6258. showToast('Error', err.message, 'error');
  6259. }
  6260. }
  6261. // PPP Profile Modal handlers
  6262. function openAddPPPProfileModal() {
  6263. document.getElementById('profile-modal-name').value = '';
  6264. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6265. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6266. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6267. document.getElementById('profile-modal-encryption').value = 'required';
  6268. document.getElementById('profile-modal-onlyone').checked = true;
  6269. document.getElementById('profile-modal-comment').value = '';
  6270. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6271. }
  6272. function closePPPProfileModal() {
  6273. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6274. }
  6275. async function submitSavePPPProfile(e) {
  6276. e.preventDefault();
  6277. const name = document.getElementById('profile-modal-name').value.trim();
  6278. const local = document.getElementById('profile-modal-local').value.trim();
  6279. const remote = document.getElementById('profile-modal-remote').value.trim();
  6280. const dns = document.getElementById('profile-modal-dns').value.trim();
  6281. const enc = document.getElementById('profile-modal-encryption').value;
  6282. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6283. const comment = document.getElementById('profile-modal-comment').value.trim();
  6284. try {
  6285. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6286. method: 'POST',
  6287. headers: { 'Content-Type': 'application/json' },
  6288. body: JSON.stringify({
  6289. id: name,
  6290. name,
  6291. local_address: local,
  6292. remote_address: remote,
  6293. dns_servers: dns,
  6294. use_encryption: enc,
  6295. only_one: onlyone,
  6296. comment
  6297. })
  6298. });
  6299. if (res.ok) {
  6300. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6301. closePPPProfileModal();
  6302. loadPPPProfiles();
  6303. } else {
  6304. const err = await res.json();
  6305. showToast('Error', err.message, 'error');
  6306. }
  6307. } catch (err) {
  6308. showToast('Error', err.message, 'error');
  6309. }
  6310. }
  6311. async function deletePPPProfile(name) {
  6312. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6313. try {
  6314. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6315. if (res.ok) {
  6316. showToast('Deleted', 'Profile removed', 'success');
  6317. loadPPPProfiles();
  6318. } else {
  6319. const err = await res.json();
  6320. showToast('Error', err.message, 'error');
  6321. }
  6322. } catch (err) {
  6323. showToast('Error', err.message, 'error');
  6324. }
  6325. }
  6326. // Server Config submissions
  6327. async function savePPPoEServerConfig(e) {
  6328. e.preventDefault();
  6329. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6330. const name = document.getElementById('pppoe-server-name').value.trim();
  6331. const iface = document.getElementById('pppoe-server-iface').value;
  6332. const profile = document.getElementById('pppoe-server-profile').value;
  6333. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6334. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6335. try {
  6336. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6337. method: 'POST',
  6338. headers: { 'Content-Type': 'application/json' },
  6339. body: JSON.stringify({
  6340. enabled,
  6341. service_name: name,
  6342. interface: iface,
  6343. default_profile: profile,
  6344. max_mtu: mtu,
  6345. max_mru: mtu,
  6346. one_session_per_host: onesession
  6347. })
  6348. });
  6349. if (res.ok) {
  6350. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6351. loadPPPServers();
  6352. fetchData(false);
  6353. } else {
  6354. const err = await res.json();
  6355. showToast('Error', err.message, 'error');
  6356. }
  6357. } catch (err) {
  6358. showToast('Error', err.message, 'error');
  6359. }
  6360. }
  6361. async function savePPTPServerConfig(e) {
  6362. e.preventDefault();
  6363. const enabled = document.getElementById('pptp-server-enabled').checked;
  6364. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6365. const profile = document.getElementById('pptp-server-profile').value;
  6366. const mppe = document.getElementById('pptp-server-mppe').checked;
  6367. try {
  6368. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6369. method: 'POST',
  6370. headers: { 'Content-Type': 'application/json' },
  6371. body: JSON.stringify({
  6372. enabled,
  6373. port,
  6374. default_profile: profile,
  6375. require_mppe: mppe
  6376. })
  6377. });
  6378. if (res.ok) {
  6379. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6380. loadPPPServers();
  6381. fetchData(false);
  6382. } else {
  6383. const err = await res.json();
  6384. showToast('Error', err.message, 'error');
  6385. }
  6386. } catch (err) {
  6387. showToast('Error', err.message, 'error');
  6388. }
  6389. }
  6390. async function saveL2TPServerConfig(e) {
  6391. e.preventDefault();
  6392. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6393. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6394. const profile = document.getElementById('l2tp-server-profile').value;
  6395. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6396. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6397. try {
  6398. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6399. method: 'POST',
  6400. headers: { 'Content-Type': 'application/json' },
  6401. body: JSON.stringify({
  6402. enabled,
  6403. port,
  6404. default_profile: profile,
  6405. use_ipsec: useipsec,
  6406. ipsec_secret: psk
  6407. })
  6408. });
  6409. if (res.ok) {
  6410. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6411. loadPPPServers();
  6412. fetchData(false);
  6413. } else {
  6414. const err = await res.json();
  6415. showToast('Error', err.message, 'error');
  6416. }
  6417. } catch (err) {
  6418. showToast('Error', err.message, 'error');
  6419. }
  6420. }
  6421. // IPSec Server Modal
  6422. function openIPSecServerModal() {
  6423. loadPPPServers();
  6424. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6425. }
  6426. function closeIPSecServerModal() {
  6427. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6428. }
  6429. async function submitSaveIPSecServer(e) {
  6430. e.preventDefault();
  6431. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6432. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6433. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6434. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6435. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6436. try {
  6437. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6438. method: 'POST',
  6439. headers: { 'Content-Type': 'application/json' },
  6440. body: JSON.stringify({
  6441. enabled,
  6442. preshared_key: psk,
  6443. pool_address: pool,
  6444. dns_servers: dns,
  6445. local_subnet: subnet
  6446. })
  6447. });
  6448. if (res.ok) {
  6449. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6450. closeIPSecServerModal();
  6451. loadPPPServers();
  6452. fetchData(false);
  6453. } else {
  6454. const err = await res.json();
  6455. showToast('Error', err.message, 'error');
  6456. }
  6457. } catch (err) {
  6458. showToast('Error', err.message, 'error');
  6459. }
  6460. }
  6461. // WireGuard Client Config Viewer
  6462. let currentWGClientConf = '';
  6463. async function openWGClientConfModal(iface, clientIP) {
  6464. try {
  6465. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6466. method: 'POST',
  6467. headers: { 'Content-Type': 'application/json' },
  6468. body: JSON.stringify({
  6469. interface: iface,
  6470. address: clientIP || '10.10.0.2/32',
  6471. dns: '1.1.1.1, 8.8.8.8'
  6472. })
  6473. });
  6474. if (res.ok) {
  6475. const data = await res.json();
  6476. currentWGClientConf = data.config;
  6477. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6478. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6479. } else {
  6480. const err = await res.json();
  6481. showToast('Error', err.message, 'error');
  6482. }
  6483. } catch (err) {
  6484. showToast('Error', err.message, 'error');
  6485. }
  6486. }
  6487. function closeWGClientConfModal() {
  6488. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6489. }
  6490. function copyWGClientConf() {
  6491. if (!currentWGClientConf) return;
  6492. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6493. }
  6494. function downloadWGClientConf() {
  6495. if (!currentWGClientConf) return;
  6496. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6497. const a = document.createElement('a');
  6498. a.href = URL.createObjectURL(blob);
  6499. a.download = 'wireguard-client.conf';
  6500. document.body.appendChild(a);
  6501. a.click();
  6502. document.body.removeChild(a);
  6503. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6504. }
  6505. // =========================================================================
  6506. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6507. // =========================================================================
  6508. state.activeDynSubTab = 'bgp-peers';
  6509. state.activeBgpSubTab = 'bgp-peers';
  6510. state.activeOspfTab = 'instances';
  6511. state.bgpInstance = null;
  6512. state.bgpPeers = [];
  6513. state.bgpNets = [];
  6514. state.bgpRoutes = [];
  6515. state.ospfInstance = null;
  6516. state.ospfInstances = [];
  6517. state.ospfAreas = [];
  6518. state.ospfAreaRanges = [];
  6519. state.ospfTemplates = [];
  6520. state.ospfLiveInterfaces = [];
  6521. state.ospfStaticNbrs = [];
  6522. state.ospfNeighbors = [];
  6523. state.ospfLSA = [];
  6524. state.ospfRoutes = [];
  6525. state.selectedOspfRow = {
  6526. instances: null,
  6527. areas: null,
  6528. 'area-ranges': null,
  6529. templates: null,
  6530. interfaces: null,
  6531. 'static-nbrs': null,
  6532. neighbors: null,
  6533. lsa: null,
  6534. };
  6535. state.ospfSort = {
  6536. instances: { col: 'name', asc: true },
  6537. areas: { col: 'name', asc: true },
  6538. ranges: { col: 'area', asc: true },
  6539. templates: { col: 'interfaces', asc: true },
  6540. live_ifaces: { col: 'interface', asc: true },
  6541. snbrs: { col: 'address', asc: true },
  6542. neighbors: { col: 'address', asc: true },
  6543. lsa: { col: 'instance', asc: true },
  6544. };
  6545. function switchBgpSubTab(subTab) {
  6546. state.activeBgpSubTab = subTab;
  6547. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6548. tabs.forEach(t => {
  6549. const el = document.getElementById(`dyn-subtab-${t}`);
  6550. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6551. if (el) el.classList.toggle('hidden', t !== subTab);
  6552. if (btn) {
  6553. if (t === subTab) {
  6554. 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';
  6555. } else {
  6556. 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';
  6557. }
  6558. }
  6559. });
  6560. }
  6561. function switchOspfTab(tabName) {
  6562. state.activeOspfTab = tabName;
  6563. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6564. tabs.forEach(t => {
  6565. const pane = document.getElementById(`ospf-pane-${t}`);
  6566. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6567. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6568. if (btn) {
  6569. if (t === tabName) {
  6570. 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';
  6571. } else {
  6572. 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';
  6573. }
  6574. }
  6575. });
  6576. }
  6577. function switchOspfSubTab(tab) {
  6578. // Legacy alias
  6579. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6580. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6581. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6582. else switchOspfTab('instances');
  6583. }
  6584. function switchDynSubTab(subTab) {
  6585. if (subTab.startsWith('bgp')) {
  6586. if (state.activeTab !== 'bgp') navigate('bgp');
  6587. switchBgpSubTab(subTab);
  6588. } else if (subTab.startsWith('ospf')) {
  6589. if (state.activeTab !== 'ospf') navigate('ospf');
  6590. switchOspfTab('instances');
  6591. }
  6592. }
  6593. async function loadDynamicRouting(showToastMsg = false) {
  6594. try {
  6595. const fetchSafeJson = async (url) => {
  6596. try {
  6597. const r = await fetch(url);
  6598. return r.ok ? await r.json() : null;
  6599. } catch (e) {
  6600. return null;
  6601. }
  6602. };
  6603. const [
  6604. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6605. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6606. selectRules, commLists, asLists
  6607. ] = await Promise.all([
  6608. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6609. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6610. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6611. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6612. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6613. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6614. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6615. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6616. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6617. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6618. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6619. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6620. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6621. fetchSafeJson(`${API_BASE}/routing/filters`),
  6622. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6623. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6624. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6625. ]);
  6626. if (sum) state.dynSummary = sum;
  6627. if (bgpInst) state.bgpInstance = bgpInst;
  6628. if (bgpPeers) state.bgpPeers = bgpPeers;
  6629. if (bgpNets) state.bgpNets = bgpNets;
  6630. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6631. if (ospfInsts) state.ospfInstances = ospfInsts;
  6632. if (ospfAreas) state.ospfAreas = ospfAreas;
  6633. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6634. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6635. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6636. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6637. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6638. if (ospfLsa) state.ospfLSA = ospfLsa;
  6639. if (filters) state.routingFilters = filters;
  6640. if (selectRules) state.routingSelectRules = selectRules;
  6641. if (commLists) state.routingCommunityLists = commLists;
  6642. if (asLists) state.routingASLists = asLists;
  6643. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6644. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6645. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6646. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6647. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6648. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6649. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6650. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6651. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6652. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6653. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6654. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6655. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6656. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6657. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6658. } catch (err) {
  6659. console.error('Failed to load dynamic routing:', err);
  6660. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6661. }
  6662. }
  6663. async function loadOspfAll() {
  6664. await loadDynamicRouting(true);
  6665. }
  6666. function renderBgpStatusPill() {
  6667. const pill = document.getElementById('bgp-live-status-pill');
  6668. if (!pill) return;
  6669. const inst = state.bgpInstance;
  6670. if (!inst || !inst.enabled) {
  6671. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6672. pill.innerText = 'BGP DISABLED';
  6673. } else if (inst.running) {
  6674. 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';
  6675. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6676. } else {
  6677. 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';
  6678. pill.innerText = 'BGP STARTING...';
  6679. }
  6680. }
  6681. function renderBgpPeers() {
  6682. const tbody = document.getElementById('bgp-peers-table-body');
  6683. if (!tbody) return;
  6684. const empty = document.getElementById('bgp-peers-empty');
  6685. const countBadge = document.getElementById('bgp-peers-count-badge');
  6686. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6687. const peers = state.bgpPeers || [];
  6688. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6689. if (navBadge) navBadge.innerText = peers.length;
  6690. if (peers.length === 0) {
  6691. tbody.innerHTML = '';
  6692. if (empty) empty.classList.remove('hidden');
  6693. return;
  6694. }
  6695. if (empty) empty.classList.add('hidden');
  6696. tbody.innerHTML = peers.map(p => {
  6697. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6698. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6699. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6700. let stateBadge = '';
  6701. if (p.disabled) {
  6702. 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>';
  6703. } else if (p.state === 'Established') {
  6704. 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>';
  6705. } else if (p.state === 'Connect' || p.state === 'Active') {
  6706. 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>`;
  6707. } else {
  6708. 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>`;
  6709. }
  6710. return `
  6711. <tr class="hover:bg-slate-800/40 transition">
  6712. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6713. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6714. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6715. <td class="py-2.5 px-3">
  6716. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6717. ${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>`}
  6718. </td>
  6719. <td class="py-2.5 px-3">${stateBadge}</td>
  6720. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6721. <td class="py-2.5 px-3 text-slate-300">
  6722. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6723. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6724. </td>
  6725. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6726. ${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> ` : ''}
  6727. ${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>` : ''}
  6728. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6729. </td>
  6730. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6731. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6732. <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'}">
  6733. ${p.disabled ? 'Enable' : 'Disable'}
  6734. </button>
  6735. <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">
  6736. Edit
  6737. </button>
  6738. <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">
  6739. Delete
  6740. </button>
  6741. </td>
  6742. </tr>
  6743. `;
  6744. }).join('');
  6745. }
  6746. function renderBgpNetworks() {
  6747. const tbody = document.getElementById('bgp-nets-table-body');
  6748. if (!tbody) return;
  6749. const empty = document.getElementById('bgp-nets-empty');
  6750. const countBadge = document.getElementById('bgp-nets-count-badge');
  6751. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6752. const nets = state.bgpNets || [];
  6753. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6754. if (navBadge) navBadge.innerText = nets.length;
  6755. if (nets.length === 0) {
  6756. tbody.innerHTML = '';
  6757. if (empty) empty.classList.remove('hidden');
  6758. return;
  6759. }
  6760. if (empty) empty.classList.add('hidden');
  6761. tbody.innerHTML = nets.map(n => `
  6762. <tr class="hover:bg-slate-800/40 transition">
  6763. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6764. <td class="py-2.5 px-3">
  6765. ${n.disabled
  6766. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6767. : '<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>'}
  6768. </td>
  6769. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6770. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6771. <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">
  6772. Delete
  6773. </button>
  6774. </td>
  6775. </tr>
  6776. `).join('');
  6777. }
  6778. function renderBgpRoutes() {
  6779. const tbody = document.getElementById('bgp-routes-table-body');
  6780. if (!tbody) return;
  6781. const empty = document.getElementById('bgp-routes-empty');
  6782. const countBadge = document.getElementById('bgp-routes-count-badge');
  6783. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6784. const routes = state.bgpRoutes || [];
  6785. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6786. if (navBadge) navBadge.innerText = routes.length;
  6787. if (routes.length === 0) {
  6788. tbody.innerHTML = '';
  6789. if (empty) empty.classList.remove('hidden');
  6790. return;
  6791. }
  6792. if (empty) empty.classList.add('hidden');
  6793. tbody.innerHTML = routes.map(r => `
  6794. <tr class="hover:bg-slate-800/40 transition">
  6795. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6796. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6797. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6798. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6799. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6800. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6801. </tr>
  6802. `).join('');
  6803. }
  6804. // =========================================================================
  6805. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6806. // =========================================================================
  6807. function sortOspfTable(tab, col) {
  6808. if (!state.ospfSort) state.ospfSort = {};
  6809. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6810. if (state.ospfSort[tab].col === col) {
  6811. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6812. } else {
  6813. state.ospfSort[tab].col = col;
  6814. state.ospfSort[tab].asc = true;
  6815. }
  6816. const asc = state.ospfSort[tab].asc;
  6817. let list = [];
  6818. if (tab === 'instances') list = state.ospfInstances || [];
  6819. else if (tab === 'areas') list = state.ospfAreas || [];
  6820. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6821. else if (tab === 'templates') list = state.ospfTemplates || [];
  6822. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6823. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6824. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6825. else if (tab === 'lsa') list = state.ospfLSA || [];
  6826. list.sort((a, b) => {
  6827. let valA = a[col] ?? '';
  6828. let valB = b[col] ?? '';
  6829. if (typeof valA === 'number' && typeof valB === 'number') {
  6830. return asc ? valA - valB : valB - valA;
  6831. }
  6832. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6833. });
  6834. if (tab === 'instances') renderOspfInstances();
  6835. else if (tab === 'areas') renderOspfAreas();
  6836. else if (tab === 'ranges') renderOspfAreaRanges();
  6837. else if (tab === 'templates') renderOspfTemplates();
  6838. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6839. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6840. else if (tab === 'neighbors') renderOspfNeighbors();
  6841. else if (tab === 'lsa') renderOspfLSA();
  6842. }
  6843. function selectOspfRow(tab, id) {
  6844. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6845. state.selectedOspfRow[tab] = id;
  6846. if (tab === 'instances') {
  6847. renderOspfInstances();
  6848. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6849. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6850. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6851. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6852. if (btnEn) btnEn.disabled = false;
  6853. if (btnDis) btnDis.disabled = false;
  6854. if (btnRem) btnRem.disabled = false;
  6855. if (btnCom) btnCom.disabled = false;
  6856. } else if (tab === 'areas') {
  6857. renderOspfAreas();
  6858. const btnEn = document.getElementById('btn-ospf-area-enable');
  6859. const btnDis = document.getElementById('btn-ospf-area-disable');
  6860. const btnRem = document.getElementById('btn-ospf-area-remove');
  6861. const btnCom = document.getElementById('btn-ospf-area-comment');
  6862. if (btnEn) btnEn.disabled = false;
  6863. if (btnDis) btnDis.disabled = false;
  6864. if (btnRem) btnRem.disabled = false;
  6865. if (btnCom) btnCom.disabled = false;
  6866. } else if (tab === 'ranges') {
  6867. renderOspfAreaRanges();
  6868. const btnEn = document.getElementById('btn-ospf-range-enable');
  6869. const btnDis = document.getElementById('btn-ospf-range-disable');
  6870. const btnRem = document.getElementById('btn-ospf-range-remove');
  6871. const btnCom = document.getElementById('btn-ospf-range-comment');
  6872. if (btnEn) btnEn.disabled = false;
  6873. if (btnDis) btnDis.disabled = false;
  6874. if (btnRem) btnRem.disabled = false;
  6875. if (btnCom) btnCom.disabled = false;
  6876. } else if (tab === 'templates') {
  6877. renderOspfTemplates();
  6878. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6879. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6880. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6881. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6882. if (btnEn) btnEn.disabled = false;
  6883. if (btnDis) btnDis.disabled = false;
  6884. if (btnRem) btnRem.disabled = false;
  6885. if (btnCom) btnCom.disabled = false;
  6886. } else if (tab === 'snbrs') {
  6887. renderOspfStaticNbrs();
  6888. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6889. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6890. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6891. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6892. if (btnEn) btnEn.disabled = false;
  6893. if (btnDis) btnDis.disabled = false;
  6894. if (btnRem) btnRem.disabled = false;
  6895. if (btnCom) btnCom.disabled = false;
  6896. }
  6897. }
  6898. // TAB 1: INSTANCES
  6899. function renderOspfInstances() {
  6900. const tbody = document.getElementById('ospf-instances-table-body');
  6901. if (!tbody) return;
  6902. const countEl = document.getElementById('ospf-instances-footer-count');
  6903. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6904. let list = state.ospfInstances || [];
  6905. if (filter) {
  6906. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6907. }
  6908. if (countEl) countEl.innerText = list.length;
  6909. const selId = state.selectedOspfRow?.instances;
  6910. tbody.innerHTML = list.map((inst, idx) => {
  6911. const isSel = inst.id === selId;
  6912. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6913. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6914. return `
  6915. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6916. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6917. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6918. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6919. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6920. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6921. </td>
  6922. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6923. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6924. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6925. </tr>
  6926. `;
  6927. }).join('');
  6928. }
  6929. // TAB 2: AREAS
  6930. function renderOspfAreas() {
  6931. const tbody = document.getElementById('ospf-areas-table-body');
  6932. if (!tbody) return;
  6933. const countEl = document.getElementById('ospf-areas-footer-count');
  6934. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6935. let list = state.ospfAreas || [];
  6936. if (filter) {
  6937. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6938. }
  6939. if (countEl) countEl.innerText = list.length;
  6940. const selId = state.selectedOspfRow?.areas;
  6941. tbody.innerHTML = list.map((a, idx) => {
  6942. const isSel = a.id === selId;
  6943. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6944. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6945. return `
  6946. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6947. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6948. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6949. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6950. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6951. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6952. </td>
  6953. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6954. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6955. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6956. </tr>
  6957. `;
  6958. }).join('');
  6959. }
  6960. // TAB 3: AREA RANGES
  6961. function renderOspfAreaRanges() {
  6962. const tbody = document.getElementById('ospf-ranges-table-body');
  6963. if (!tbody) return;
  6964. const countEl = document.getElementById('ospf-ranges-footer-count');
  6965. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6966. let list = state.ospfAreaRanges || [];
  6967. if (filter) {
  6968. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6969. }
  6970. if (countEl) countEl.innerText = list.length;
  6971. const selId = state.selectedOspfRow?.['area-ranges'];
  6972. tbody.innerHTML = list.map((r, idx) => {
  6973. const isSel = r.id === selId;
  6974. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6975. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6976. return `
  6977. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6978. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6979. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6980. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6981. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6982. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6983. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6984. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6985. </tr>
  6986. `;
  6987. }).join('');
  6988. }
  6989. // TAB 4: INTERFACE TEMPLATES
  6990. function renderOspfTemplates() {
  6991. const tbody = document.getElementById('ospf-templates-table-body');
  6992. if (!tbody) return;
  6993. const countEl = document.getElementById('ospf-templates-footer-count');
  6994. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  6995. let list = state.ospfTemplates || [];
  6996. if (filter) {
  6997. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  6998. }
  6999. if (countEl) countEl.innerText = list.length;
  7000. const selId = state.selectedOspfRow?.templates;
  7001. tbody.innerHTML = list.map((t, idx) => {
  7002. const isSel = t.id === selId;
  7003. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7004. const ifaces = t.interfaces || t.interface || 'all';
  7005. const nets = t.networks || t.network || '';
  7006. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7007. return `
  7008. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7009. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7010. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7011. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7012. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7013. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7014. </td>
  7015. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7016. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7017. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7018. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7019. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7020. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7021. </tr>
  7022. `;
  7023. }).join('');
  7024. }
  7025. // TAB 5: LIVE INTERFACES
  7026. function renderOspfLiveInterfaces() {
  7027. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7028. if (!tbody) return;
  7029. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7030. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7031. let list = state.ospfLiveInterfaces || [];
  7032. if (filter) {
  7033. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7034. }
  7035. if (countEl) countEl.innerText = list.length;
  7036. tbody.innerHTML = list.map(i => `
  7037. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7038. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7039. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7040. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7041. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7042. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7043. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7044. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7045. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7046. </tr>
  7047. `).join('');
  7048. }
  7049. // TAB 6: STATIC NEIGHBORS
  7050. function renderOspfStaticNbrs() {
  7051. const tbody = document.getElementById('ospf-snbrs-table-body');
  7052. if (!tbody) return;
  7053. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7054. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7055. let list = state.ospfStaticNbrs || [];
  7056. if (filter) {
  7057. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7058. }
  7059. if (countEl) countEl.innerText = list.length;
  7060. const selId = state.selectedOspfRow?.['static-nbrs'];
  7061. tbody.innerHTML = list.map((n, idx) => {
  7062. const isSel = n.id === selId;
  7063. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7064. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7065. return `
  7066. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7067. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7068. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7069. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7070. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7071. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7072. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7073. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7074. </tr>
  7075. `;
  7076. }).join('');
  7077. }
  7078. // TAB 7: LIVE NEIGHBORS
  7079. function renderOspfNeighbors() {
  7080. const tbody = document.getElementById('ospf-neighbors-table-body');
  7081. if (!tbody) return;
  7082. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7083. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7084. let list = state.ospfNeighbors || [];
  7085. if (filter) {
  7086. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7087. }
  7088. if (countEl) countEl.innerText = list.length;
  7089. tbody.innerHTML = list.map(n => `
  7090. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7091. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7092. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7093. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7094. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7095. </td>
  7096. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7097. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7098. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7099. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7100. </tr>
  7101. `).join('');
  7102. }
  7103. // TAB 8: LINK-STATE DATABASE (LSA)
  7104. function renderOspfLSA() {
  7105. const tbody = document.getElementById('ospf-lsa-table-body');
  7106. if (!tbody) return;
  7107. const countEl = document.getElementById('ospf-lsa-footer-count');
  7108. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7109. let list = state.ospfLSA || [];
  7110. if (filter) {
  7111. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7112. }
  7113. if (countEl) countEl.innerText = list.length;
  7114. tbody.innerHTML = list.map(l => `
  7115. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7116. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7117. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7118. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7119. </td>
  7120. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7121. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7122. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7123. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7124. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7125. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7126. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7127. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7128. </tr>
  7129. `).join('');
  7130. }
  7131. function renderOspfStatusPill() {
  7132. // Maintained for backward compatibility
  7133. const pill = document.getElementById('ospf-live-status-pill');
  7134. if (!pill) return;
  7135. 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';
  7136. pill.innerText = 'OSPF ACTIVE';
  7137. }
  7138. function renderOspfInterfaces() {
  7139. renderOspfTemplates();
  7140. }
  7141. function renderOspfRoutes() {
  7142. // Routes retained in background
  7143. }
  7144. // BGP Modals & Actions
  7145. function openBgpInstanceModal() {
  7146. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7147. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7148. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7149. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7150. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7151. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7152. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7153. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7154. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7155. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7156. }
  7157. function closeBgpInstanceModal() {
  7158. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7159. }
  7160. async function submitBgpInstance(e) {
  7161. e.preventDefault();
  7162. const payload = {
  7163. enabled: document.getElementById('modal-bgp-enabled').checked,
  7164. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7165. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7166. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7167. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7168. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7169. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7170. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7171. };
  7172. try {
  7173. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7174. method: 'POST',
  7175. headers: { 'Content-Type': 'application/json' },
  7176. body: JSON.stringify(payload)
  7177. });
  7178. if (res.ok) {
  7179. closeBgpInstanceModal();
  7180. showToast('Success', 'BGP instance configuration updated', 'success');
  7181. loadDynamicRouting();
  7182. } else {
  7183. const err = await res.json();
  7184. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7185. }
  7186. } catch (err) {
  7187. showToast('Error', err.message, 'error');
  7188. }
  7189. }
  7190. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7191. function switchBgpPeerModalTab(tab) {
  7192. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7193. tabs.forEach(t => {
  7194. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7195. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7196. if (t === tab) {
  7197. if (pane) pane.classList.remove('hidden');
  7198. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7199. } else {
  7200. if (pane) pane.classList.add('hidden');
  7201. 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';
  7202. }
  7203. });
  7204. }
  7205. function addOutputNetworkRow(val = '') {
  7206. const container = document.getElementById('modal-bgp-output-networks-container');
  7207. if (!container) return;
  7208. const row = document.createElement('div');
  7209. row.className = 'flex items-center gap-2 output-net-row';
  7210. row.innerHTML = `
  7211. <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">
  7212. <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>
  7213. `;
  7214. container.appendChild(row);
  7215. }
  7216. function parseBgpTime(val) {
  7217. if (!val) return 0;
  7218. val = String(val).trim();
  7219. if (val.includes(':')) {
  7220. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7221. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7222. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7223. }
  7224. return parseInt(val, 10) || 0;
  7225. }
  7226. function formatBgpTime(secs) {
  7227. if (!secs || secs <= 0) return '00:00:00';
  7228. const h = Math.floor(secs / 3600);
  7229. const m = Math.floor((secs % 3600) / 60);
  7230. const s = secs % 60;
  7231. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7232. }
  7233. function populateBgpRoutingTables() {
  7234. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7235. if (!sel) return;
  7236. const cur = sel.value || 'main';
  7237. sel.innerHTML = '<option value="main">main</option>';
  7238. (state.routingTables || []).forEach(t => {
  7239. if (t.name !== 'main') {
  7240. const opt = document.createElement('option');
  7241. opt.value = t.name;
  7242. opt.innerText = t.name;
  7243. sel.appendChild(opt);
  7244. }
  7245. });
  7246. sel.value = cur;
  7247. }
  7248. function openAddBgpPeerModal() {
  7249. document.getElementById('bgp-peer-form').reset();
  7250. document.getElementById('modal-bgp-peer-id').value = '';
  7251. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7252. // General Tab
  7253. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7254. document.getElementById('modal-bgp-peer-comment').value = '';
  7255. document.getElementById('modal-bgp-peer-name').value = '';
  7256. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7257. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7258. document.getElementById('modal-bgp-peer-local-as').value = '';
  7259. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7260. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7261. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7262. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7263. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7264. document.getElementById('modal-bgp-peer-router-id').value = '';
  7265. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7266. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7267. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7268. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7269. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7270. document.getElementById('modal-bgp-peer-local-port').value = '';
  7271. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7272. document.getElementById('modal-bgp-peer-password').value = '';
  7273. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7274. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7275. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7276. document.getElementById('modal-bgp-peer-connect').checked = true;
  7277. document.getElementById('modal-bgp-peer-listen').checked = true;
  7278. // Extra Tab
  7279. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7280. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7281. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7282. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7283. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7284. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7285. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7286. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7287. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7288. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7289. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7290. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7291. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7292. // Attributes Tab
  7293. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7294. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7295. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7296. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7297. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7298. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7299. // Filter Tab
  7300. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7301. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7302. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7303. populateBgpRoutingTables();
  7304. const container = document.getElementById('modal-bgp-output-networks-container');
  7305. if (container) {
  7306. container.innerHTML = '';
  7307. addOutputNetworkRow('');
  7308. }
  7309. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7310. if (removeBtn) removeBtn.classList.add('hidden');
  7311. switchBgpPeerModalTab('general');
  7312. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7313. }
  7314. function openEditBgpPeerModal(id) {
  7315. const p = (state.bgpPeers || []).find(item => item.id === id);
  7316. if (!p) return;
  7317. populateBgpRoutingTables();
  7318. document.getElementById('modal-bgp-peer-id').value = p.id;
  7319. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7320. // General Tab
  7321. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7322. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7323. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7324. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7325. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7326. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7327. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7328. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7329. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7330. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7331. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7332. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7333. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7334. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7335. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7336. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7337. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7338. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7339. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7340. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7341. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7342. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7343. // Extra Tab
  7344. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7345. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7346. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7347. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7348. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7349. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7350. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7351. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7352. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7353. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7354. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7355. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7356. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7357. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7358. // Attributes Tab
  7359. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7360. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7361. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7362. 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;
  7363. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7364. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7365. // Filter Tab
  7366. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7367. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7368. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7369. // Output Networks
  7370. const container = document.getElementById('modal-bgp-output-networks-container');
  7371. if (container) {
  7372. container.innerHTML = '';
  7373. if (p.output_networks && p.output_networks.length > 0) {
  7374. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7375. } else {
  7376. addOutputNetworkRow('');
  7377. }
  7378. }
  7379. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7380. if (removeBtn) removeBtn.classList.remove('hidden');
  7381. switchBgpPeerModalTab('general');
  7382. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7383. }
  7384. function copyCurrentBgpPeer() {
  7385. document.getElementById('modal-bgp-peer-id').value = '';
  7386. const nameEl = document.getElementById('modal-bgp-peer-name');
  7387. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7388. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7389. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7390. if (removeBtn) removeBtn.classList.add('hidden');
  7391. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7392. }
  7393. function removeCurrentBgpPeer() {
  7394. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7395. if (!id) return;
  7396. deleteBgpPeer(id);
  7397. closeBgpPeerModal();
  7398. }
  7399. function closeBgpPeerModal() {
  7400. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7401. }
  7402. function getBgpPeerFormData() {
  7403. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7404. const outputNetworks = [];
  7405. netInputs.forEach(inp => {
  7406. const v = inp.value.trim();
  7407. if (v) outputNetworks.push(v);
  7408. });
  7409. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7410. return {
  7411. id: document.getElementById('modal-bgp-peer-id').value,
  7412. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7413. enabled: enabled,
  7414. disabled: !enabled,
  7415. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7416. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7417. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7418. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7419. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7420. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7421. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7422. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7423. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7424. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7425. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7426. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7427. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7428. password: document.getElementById('modal-bgp-peer-password').value,
  7429. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7430. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7431. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7432. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7433. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7434. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7435. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7436. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7437. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7438. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7439. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7440. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7441. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7442. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7443. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7444. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7445. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7446. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7447. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7448. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7449. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7450. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7451. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7452. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7453. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7454. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7455. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7456. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7457. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7458. output_networks: outputNetworks
  7459. };
  7460. }
  7461. async function submitBgpPeer(e) {
  7462. if (e) e.preventDefault();
  7463. const payload = getBgpPeerFormData();
  7464. try {
  7465. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7466. method: 'POST',
  7467. headers: { 'Content-Type': 'application/json' },
  7468. body: JSON.stringify(payload)
  7469. });
  7470. if (res.ok) {
  7471. closeBgpPeerModal();
  7472. showToast('Success', 'BGP Connection saved', 'success');
  7473. loadDynamicRouting();
  7474. } else {
  7475. const err = await res.json();
  7476. showToast('Error', err.error || 'Failed to save peer', 'error');
  7477. }
  7478. } catch (err) {
  7479. showToast('Error', err.message, 'error');
  7480. }
  7481. }
  7482. async function applyBgpPeerModal(e) {
  7483. if (e) e.preventDefault();
  7484. const payload = getBgpPeerFormData();
  7485. try {
  7486. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7487. method: 'POST',
  7488. headers: { 'Content-Type': 'application/json' },
  7489. body: JSON.stringify(payload)
  7490. });
  7491. if (res.ok) {
  7492. const data = await res.json();
  7493. if (data.peer && data.peer.id) {
  7494. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7495. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7496. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7497. }
  7498. showToast('Applied', 'BGP Connection applied', 'success');
  7499. loadDynamicRouting();
  7500. } else {
  7501. const err = await res.json();
  7502. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7503. }
  7504. } catch (err) {
  7505. showToast('Error', err.message, 'error');
  7506. }
  7507. }
  7508. async function deleteBgpPeer(id) {
  7509. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7510. try {
  7511. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7512. if (res.ok) {
  7513. showToast('Deleted', 'BGP peer removed', 'success');
  7514. loadDynamicRouting();
  7515. }
  7516. } catch (err) {
  7517. showToast('Error', err.message, 'error');
  7518. }
  7519. }
  7520. async function toggleBgpPeerState(id, disabled) {
  7521. try {
  7522. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7523. method: 'POST',
  7524. headers: { 'Content-Type': 'application/json' },
  7525. body: JSON.stringify({ disabled })
  7526. });
  7527. if (res.ok) {
  7528. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7529. loadDynamicRouting();
  7530. }
  7531. } catch (err) {
  7532. showToast('Error', err.message, 'error');
  7533. }
  7534. }
  7535. function openAddBgpNetworkModal() {
  7536. document.getElementById('bgp-network-form').reset();
  7537. document.getElementById('modal-bgp-net-id').value = '';
  7538. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7539. }
  7540. function closeBgpNetworkModal() {
  7541. document.getElementById('bgp-network-modal').classList.add('hidden');
  7542. }
  7543. async function submitBgpNetwork(e) {
  7544. e.preventDefault();
  7545. const payload = {
  7546. id: document.getElementById('modal-bgp-net-id').value,
  7547. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7548. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7549. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7550. };
  7551. try {
  7552. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7553. method: 'POST',
  7554. headers: { 'Content-Type': 'application/json' },
  7555. body: JSON.stringify(payload)
  7556. });
  7557. if (res.ok) {
  7558. closeBgpNetworkModal();
  7559. showToast('Success', 'BGP network advertisement saved', 'success');
  7560. loadDynamicRouting();
  7561. } else {
  7562. const err = await res.json();
  7563. showToast('Error', err.error || 'Failed to save network', 'error');
  7564. }
  7565. } catch (err) {
  7566. showToast('Error', err.message, 'error');
  7567. }
  7568. }
  7569. async function deleteBgpNetwork(id) {
  7570. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7571. try {
  7572. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7573. if (res.ok) {
  7574. showToast('Deleted', 'Network advertisement removed', 'success');
  7575. loadDynamicRouting();
  7576. }
  7577. } catch (err) {
  7578. showToast('Error', err.message, 'error');
  7579. }
  7580. }
  7581. // =========================================================================
  7582. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7583. // =========================================================================
  7584. // --- 1. OSPF INSTANCE ---
  7585. function openOspfInstanceModal(id = null) {
  7586. const isEdit = !!id;
  7587. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7588. id: '',
  7589. name: 'Default',
  7590. version: 2,
  7591. vrf: 'main',
  7592. router_id: '192.168.131.56',
  7593. routing_table: 'main',
  7594. enabled: true,
  7595. redistribute_connected: false,
  7596. redistribute_static: true,
  7597. redistribute_bgp: false,
  7598. comment: ''
  7599. };
  7600. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7601. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7602. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7603. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7604. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7605. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7606. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7607. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7608. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7609. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7610. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7611. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7612. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7613. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7614. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7615. }
  7616. function openEditOspfInstanceModal(id) {
  7617. openOspfInstanceModal(id);
  7618. }
  7619. function closeOspfInstanceModal() {
  7620. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7621. }
  7622. async function submitOspfInstance(e) {
  7623. if (e) e.preventDefault();
  7624. const payload = {
  7625. id: document.getElementById('modal-ospf-inst-id').value,
  7626. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7627. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7628. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7629. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7630. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7631. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7632. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7633. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7634. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7635. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7636. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7637. };
  7638. try {
  7639. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7640. method: 'POST',
  7641. headers: { 'Content-Type': 'application/json' },
  7642. body: JSON.stringify(payload)
  7643. });
  7644. if (res.ok) {
  7645. closeOspfInstanceModal();
  7646. showToast('Saved', 'OSPF instance updated', 'success');
  7647. loadDynamicRouting();
  7648. } else {
  7649. const err = await res.json();
  7650. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7651. }
  7652. } catch (err) {
  7653. showToast('Error', err.message, 'error');
  7654. }
  7655. }
  7656. function applyOspfInstanceForm() {
  7657. submitOspfInstance(null);
  7658. }
  7659. function copyOspfInstance() {
  7660. document.getElementById('modal-ospf-inst-id').value = '';
  7661. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7662. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7663. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7664. }
  7665. async function deleteCurrentOspfInstance() {
  7666. const id = document.getElementById('modal-ospf-inst-id').value;
  7667. if (!id) return;
  7668. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7669. try {
  7670. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7671. if (res.ok) {
  7672. closeOspfInstanceModal();
  7673. showToast('Removed', 'OSPF instance deleted', 'success');
  7674. loadDynamicRouting();
  7675. }
  7676. } catch (err) {
  7677. showToast('Error', err.message, 'error');
  7678. }
  7679. }
  7680. async function enableSelectedOspfInstance() {
  7681. const id = state.selectedOspfRow?.instances;
  7682. if (!id) return;
  7683. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7684. method: 'POST',
  7685. headers: { 'Content-Type': 'application/json' },
  7686. body: JSON.stringify({ disabled: false })
  7687. });
  7688. loadDynamicRouting();
  7689. }
  7690. async function disableSelectedOspfInstance() {
  7691. const id = state.selectedOspfRow?.instances;
  7692. if (!id) return;
  7693. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7694. method: 'POST',
  7695. headers: { 'Content-Type': 'application/json' },
  7696. body: JSON.stringify({ disabled: true })
  7697. });
  7698. loadDynamicRouting();
  7699. }
  7700. async function removeSelectedOspfInstance() {
  7701. const id = state.selectedOspfRow?.instances;
  7702. if (!id) return;
  7703. if (!confirm('Delete selected OSPF instance?')) return;
  7704. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7705. loadDynamicRouting();
  7706. }
  7707. async function promptCommentOspfInstance() {
  7708. const id = state.selectedOspfRow?.instances;
  7709. if (!id) return;
  7710. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7711. if (!inst) return;
  7712. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7713. if (comment === null) return;
  7714. inst.comment = comment;
  7715. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7716. method: 'POST',
  7717. headers: { 'Content-Type': 'application/json' },
  7718. body: JSON.stringify(inst)
  7719. });
  7720. loadDynamicRouting();
  7721. }
  7722. // --- 2. OSPF AREA ---
  7723. function populateOspfAreaDropdowns() {
  7724. const instSelect = document.getElementById('modal-ospf-area-instance');
  7725. if (instSelect) {
  7726. const cur = instSelect.value;
  7727. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7728. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7729. if (cur) instSelect.value = cur;
  7730. }
  7731. }
  7732. function openOspfAreaModal(id = null) {
  7733. const isEdit = !!id;
  7734. populateOspfAreaDropdowns();
  7735. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7736. id: '',
  7737. name: 'Default',
  7738. instance: 'Default',
  7739. area_id: '0.0.0.0',
  7740. area_type: 'default',
  7741. default_cost: 1,
  7742. no_summaries: false,
  7743. disabled: false,
  7744. comment: ''
  7745. };
  7746. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7747. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7748. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7749. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7750. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7751. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7752. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7753. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7754. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7755. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7756. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7757. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7758. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7759. }
  7760. function openEditOspfAreaModal(id) {
  7761. openOspfAreaModal(id);
  7762. }
  7763. function closeOspfAreaModal() {
  7764. document.getElementById('ospf-area-modal').classList.add('hidden');
  7765. }
  7766. async function submitOspfArea(e) {
  7767. if (e) e.preventDefault();
  7768. const payload = {
  7769. id: document.getElementById('modal-ospf-area-id').value,
  7770. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7771. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7772. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7773. area_type: document.getElementById('modal-ospf-area-type').value,
  7774. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7775. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7776. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7777. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7778. };
  7779. try {
  7780. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7781. method: 'POST',
  7782. headers: { 'Content-Type': 'application/json' },
  7783. body: JSON.stringify(payload)
  7784. });
  7785. if (res.ok) {
  7786. closeOspfAreaModal();
  7787. showToast('Saved', 'OSPF area saved', 'success');
  7788. loadDynamicRouting();
  7789. } else {
  7790. const err = await res.json();
  7791. showToast('Error', err.error || 'Failed to save area', 'error');
  7792. }
  7793. } catch (err) {
  7794. showToast('Error', err.message, 'error');
  7795. }
  7796. }
  7797. function applyOspfAreaForm() {
  7798. submitOspfArea(null);
  7799. }
  7800. function copyOspfArea() {
  7801. document.getElementById('modal-ospf-area-id').value = '';
  7802. document.getElementById('modal-ospf-area-name').value += '-copy';
  7803. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7804. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7805. }
  7806. async function deleteCurrentOspfArea() {
  7807. const id = document.getElementById('modal-ospf-area-id').value;
  7808. if (!id) return;
  7809. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7810. try {
  7811. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7812. if (res.ok) {
  7813. closeOspfAreaModal();
  7814. showToast('Removed', 'OSPF area deleted', 'success');
  7815. loadDynamicRouting();
  7816. }
  7817. } catch (err) {
  7818. showToast('Error', err.message, 'error');
  7819. }
  7820. }
  7821. async function enableSelectedOspfArea() {
  7822. const id = state.selectedOspfRow?.areas;
  7823. if (!id) return;
  7824. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7825. method: 'POST',
  7826. headers: { 'Content-Type': 'application/json' },
  7827. body: JSON.stringify({ disabled: false })
  7828. });
  7829. loadDynamicRouting();
  7830. }
  7831. async function disableSelectedOspfArea() {
  7832. const id = state.selectedOspfRow?.areas;
  7833. if (!id) return;
  7834. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7835. method: 'POST',
  7836. headers: { 'Content-Type': 'application/json' },
  7837. body: JSON.stringify({ disabled: true })
  7838. });
  7839. loadDynamicRouting();
  7840. }
  7841. async function removeSelectedOspfArea() {
  7842. const id = state.selectedOspfRow?.areas;
  7843. if (!id) return;
  7844. if (!confirm('Delete selected OSPF area?')) return;
  7845. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7846. loadDynamicRouting();
  7847. }
  7848. async function promptCommentOspfArea() {
  7849. const id = state.selectedOspfRow?.areas;
  7850. if (!id) return;
  7851. const area = (state.ospfAreas || []).find(a => a.id === id);
  7852. if (!area) return;
  7853. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7854. if (comment === null) return;
  7855. area.comment = comment;
  7856. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7857. method: 'POST',
  7858. headers: { 'Content-Type': 'application/json' },
  7859. body: JSON.stringify(area)
  7860. });
  7861. loadDynamicRouting();
  7862. }
  7863. // --- 3. OSPF AREA RANGE ---
  7864. function populateAreaRangeDropdowns() {
  7865. const select = document.getElementById('modal-ospf-range-area');
  7866. if (select) {
  7867. const cur = select.value;
  7868. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7869. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7870. if (cur) select.value = cur;
  7871. }
  7872. }
  7873. function openOspfAreaRangeModal(id = null) {
  7874. const isEdit = !!id;
  7875. populateAreaRangeDropdowns();
  7876. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7877. id: '',
  7878. area: 'Default',
  7879. prefix: '',
  7880. cost: 1,
  7881. advertise: true,
  7882. disabled: false,
  7883. comment: ''
  7884. };
  7885. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7886. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7887. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7888. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7889. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7890. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7891. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7892. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7893. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7894. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7895. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7896. }
  7897. function openEditOspfAreaRangeModal(id) {
  7898. openOspfAreaRangeModal(id);
  7899. }
  7900. function closeOspfAreaRangeModal() {
  7901. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7902. }
  7903. async function submitOspfAreaRange(e) {
  7904. if (e) e.preventDefault();
  7905. const payload = {
  7906. id: document.getElementById('modal-ospf-range-id').value,
  7907. area: document.getElementById('modal-ospf-range-area').value,
  7908. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7909. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7910. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7911. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7912. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7913. };
  7914. try {
  7915. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7916. method: 'POST',
  7917. headers: { 'Content-Type': 'application/json' },
  7918. body: JSON.stringify(payload)
  7919. });
  7920. if (res.ok) {
  7921. closeOspfAreaRangeModal();
  7922. showToast('Saved', 'Area range saved', 'success');
  7923. loadDynamicRouting();
  7924. } else {
  7925. const err = await res.json();
  7926. showToast('Error', err.error || 'Failed to save area range', 'error');
  7927. }
  7928. } catch (err) {
  7929. showToast('Error', err.message, 'error');
  7930. }
  7931. }
  7932. function applyOspfAreaRangeForm() {
  7933. submitOspfAreaRange(null);
  7934. }
  7935. async function deleteCurrentOspfAreaRange() {
  7936. const id = document.getElementById('modal-ospf-range-id').value;
  7937. if (!id) return;
  7938. if (!confirm('Delete this area range?')) return;
  7939. try {
  7940. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7941. closeOspfAreaRangeModal();
  7942. showToast('Removed', 'Area range removed', 'success');
  7943. loadDynamicRouting();
  7944. } catch (err) {
  7945. showToast('Error', err.message, 'error');
  7946. }
  7947. }
  7948. async function enableSelectedOspfAreaRange() {
  7949. const id = state.selectedOspfRow?.['area-ranges'];
  7950. if (!id) return;
  7951. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7952. if (!r) return;
  7953. r.disabled = false;
  7954. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7955. loadDynamicRouting();
  7956. }
  7957. async function disableSelectedOspfAreaRange() {
  7958. const id = state.selectedOspfRow?.['area-ranges'];
  7959. if (!id) return;
  7960. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7961. if (!r) return;
  7962. r.disabled = true;
  7963. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7964. loadDynamicRouting();
  7965. }
  7966. async function removeSelectedOspfAreaRange() {
  7967. const id = state.selectedOspfRow?.['area-ranges'];
  7968. if (!id) return;
  7969. if (!confirm('Delete selected area range?')) return;
  7970. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7971. loadDynamicRouting();
  7972. }
  7973. async function promptCommentOspfAreaRange() {
  7974. const id = state.selectedOspfRow?.['area-ranges'];
  7975. if (!id) return;
  7976. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7977. if (!r) return;
  7978. const comment = prompt('Enter comment for area range:', r.comment || '');
  7979. if (comment === null) return;
  7980. r.comment = comment;
  7981. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7982. loadDynamicRouting();
  7983. }
  7984. // --- 4. OSPF INTERFACE TEMPLATE ---
  7985. function switchOspfTemplateTab(tab) {
  7986. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  7987. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  7988. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  7989. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  7990. if (tab === 'general') {
  7991. if (tabGen) tabGen.classList.remove('hidden');
  7992. if (tabAuth) tabAuth.classList.add('hidden');
  7993. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7994. 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';
  7995. } else {
  7996. if (tabGen) tabGen.classList.add('hidden');
  7997. if (tabAuth) tabAuth.classList.remove('hidden');
  7998. 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';
  7999. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8000. }
  8001. }
  8002. function populateTemplateAreaDropdowns() {
  8003. const select = document.getElementById('modal-ospf-tmpl-area');
  8004. if (select) {
  8005. const cur = select.value;
  8006. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8007. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8008. if (cur) select.value = cur;
  8009. }
  8010. }
  8011. function openOspfTemplateModal(id = null) {
  8012. const isEdit = !!id;
  8013. populateTemplateAreaDropdowns();
  8014. switchOspfTemplateTab('general');
  8015. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8016. id: '',
  8017. interfaces: '',
  8018. area: 'Default',
  8019. networks: '',
  8020. network_type: 'broadcast',
  8021. cost: 1,
  8022. priority: 128,
  8023. passive: false,
  8024. hello_interval: 10,
  8025. dead_interval: 40,
  8026. auth: 'none',
  8027. auth_key: '',
  8028. disabled: false,
  8029. comment: ''
  8030. };
  8031. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8032. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8033. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8034. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8035. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8036. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8037. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8038. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8039. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8040. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8041. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8042. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8043. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8044. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8045. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8046. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8047. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8048. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8049. }
  8050. function openEditOspfTemplateModal(id) {
  8051. openOspfTemplateModal(id);
  8052. }
  8053. function closeOspfTemplateModal() {
  8054. document.getElementById('ospf-template-modal').classList.add('hidden');
  8055. }
  8056. async function submitOspfTemplate(e) {
  8057. if (e) e.preventDefault();
  8058. const payload = {
  8059. id: document.getElementById('modal-ospf-tmpl-id').value,
  8060. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8061. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8062. area: document.getElementById('modal-ospf-tmpl-area').value,
  8063. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8064. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8065. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8066. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8067. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8068. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8069. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8070. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8071. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8072. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8073. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8074. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8075. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8076. };
  8077. try {
  8078. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8079. method: 'POST',
  8080. headers: { 'Content-Type': 'application/json' },
  8081. body: JSON.stringify(payload)
  8082. });
  8083. if (res.ok) {
  8084. closeOspfTemplateModal();
  8085. showToast('Saved', 'Interface template saved', 'success');
  8086. loadDynamicRouting();
  8087. } else {
  8088. const err = await res.json();
  8089. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8090. }
  8091. } catch (err) {
  8092. showToast('Error', err.message, 'error');
  8093. }
  8094. }
  8095. function applyOspfTemplateForm() {
  8096. submitOspfTemplate(null);
  8097. }
  8098. function copyOspfTemplate() {
  8099. document.getElementById('modal-ospf-tmpl-id').value = '';
  8100. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8101. showToast('Copied', 'Duplicated as new template', 'info');
  8102. }
  8103. async function deleteCurrentOspfTemplate() {
  8104. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8105. if (!id) return;
  8106. if (!confirm('Delete this interface template?')) return;
  8107. try {
  8108. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8109. closeOspfTemplateModal();
  8110. showToast('Removed', 'Interface template deleted', 'success');
  8111. loadDynamicRouting();
  8112. } catch (err) {
  8113. showToast('Error', err.message, 'error');
  8114. }
  8115. }
  8116. async function enableSelectedOspfTemplate() {
  8117. const id = state.selectedOspfRow?.templates;
  8118. if (!id) return;
  8119. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8120. method: 'POST',
  8121. headers: { 'Content-Type': 'application/json' },
  8122. body: JSON.stringify({ disabled: false })
  8123. });
  8124. loadDynamicRouting();
  8125. }
  8126. async function disableSelectedOspfTemplate() {
  8127. const id = state.selectedOspfRow?.templates;
  8128. if (!id) return;
  8129. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8130. method: 'POST',
  8131. headers: { 'Content-Type': 'application/json' },
  8132. body: JSON.stringify({ disabled: true })
  8133. });
  8134. loadDynamicRouting();
  8135. }
  8136. async function removeSelectedOspfTemplate() {
  8137. const id = state.selectedOspfRow?.templates;
  8138. if (!id) return;
  8139. if (!confirm('Delete selected interface template?')) return;
  8140. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8141. loadDynamicRouting();
  8142. }
  8143. async function promptCommentOspfTemplate() {
  8144. const id = state.selectedOspfRow?.templates;
  8145. if (!id) return;
  8146. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8147. if (!tmpl) return;
  8148. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8149. if (comment === null) return;
  8150. tmpl.comment = comment;
  8151. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8152. method: 'POST',
  8153. headers: { 'Content-Type': 'application/json' },
  8154. body: JSON.stringify(tmpl)
  8155. });
  8156. loadDynamicRouting();
  8157. }
  8158. // --- 5. OSPF STATIC NEIGHBOR ---
  8159. function populateStaticNbrAreaDropdowns() {
  8160. const select = document.getElementById('modal-ospf-snbr-area');
  8161. if (select) {
  8162. const cur = select.value;
  8163. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8164. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8165. if (cur) select.value = cur;
  8166. }
  8167. }
  8168. function openOspfStaticNbrModal(id = null) {
  8169. const isEdit = !!id;
  8170. populateStaticNbrAreaDropdowns();
  8171. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8172. id: '',
  8173. address: '',
  8174. area: 'Default',
  8175. poll_interval: 120,
  8176. cost: 1,
  8177. disabled: false,
  8178. comment: ''
  8179. };
  8180. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8181. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8182. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8183. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8184. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8185. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8186. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8187. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8188. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8189. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8190. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8191. }
  8192. function openEditOspfStaticNbrModal(id) {
  8193. openOspfStaticNbrModal(id);
  8194. }
  8195. function closeOspfStaticNbrModal() {
  8196. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8197. }
  8198. async function submitOspfStaticNbr(e) {
  8199. if (e) e.preventDefault();
  8200. const payload = {
  8201. id: document.getElementById('modal-ospf-snbr-id').value,
  8202. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8203. area: document.getElementById('modal-ospf-snbr-area').value,
  8204. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8205. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8206. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8207. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8208. };
  8209. try {
  8210. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8211. method: 'POST',
  8212. headers: { 'Content-Type': 'application/json' },
  8213. body: JSON.stringify(payload)
  8214. });
  8215. if (res.ok) {
  8216. closeOspfStaticNbrModal();
  8217. showToast('Saved', 'Static neighbor saved', 'success');
  8218. loadDynamicRouting();
  8219. } else {
  8220. const err = await res.json();
  8221. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8222. }
  8223. } catch (err) {
  8224. showToast('Error', err.message, 'error');
  8225. }
  8226. }
  8227. function applyOspfStaticNbrForm() {
  8228. submitOspfStaticNbr(null);
  8229. }
  8230. async function deleteCurrentOspfStaticNbr() {
  8231. const id = document.getElementById('modal-ospf-snbr-id').value;
  8232. if (!id) return;
  8233. if (!confirm('Delete this static neighbor?')) return;
  8234. try {
  8235. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8236. closeOspfStaticNbrModal();
  8237. showToast('Removed', 'Static neighbor removed', 'success');
  8238. loadDynamicRouting();
  8239. } catch (err) {
  8240. showToast('Error', err.message, 'error');
  8241. }
  8242. }
  8243. async function enableSelectedOspfStaticNbr() {
  8244. const id = state.selectedOspfRow?.['static-nbrs'];
  8245. if (!id) return;
  8246. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8247. if (!n) return;
  8248. n.disabled = false;
  8249. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8250. loadDynamicRouting();
  8251. }
  8252. async function disableSelectedOspfStaticNbr() {
  8253. const id = state.selectedOspfRow?.['static-nbrs'];
  8254. if (!id) return;
  8255. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8256. if (!n) return;
  8257. n.disabled = true;
  8258. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8259. loadDynamicRouting();
  8260. }
  8261. async function removeSelectedOspfStaticNbr() {
  8262. const id = state.selectedOspfRow?.['static-nbrs'];
  8263. if (!id) return;
  8264. if (!confirm('Delete selected static neighbor?')) return;
  8265. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8266. loadDynamicRouting();
  8267. }
  8268. async function promptCommentOspfStaticNbr() {
  8269. const id = state.selectedOspfRow?.['static-nbrs'];
  8270. if (!id) return;
  8271. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8272. if (!n) return;
  8273. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8274. if (comment === null) return;
  8275. n.comment = comment;
  8276. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8277. loadDynamicRouting();
  8278. }
  8279. // Backward-compat aliases
  8280. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8281. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8282. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8283. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8284. function deleteOspfInterface(id) {
  8285. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8286. }
  8287. function toggleOspfInterfaceState(id, disabled) {
  8288. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8289. method: 'POST',
  8290. headers: { 'Content-Type': 'application/json' },
  8291. body: JSON.stringify({ disabled })
  8292. }).then(() => loadDynamicRouting());
  8293. }
  8294. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8295. function deleteOspfArea(id) {
  8296. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8297. }
  8298. // ============================================================================
  8299. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8300. // ============================================================================
  8301. function switchBridgeSubTab(tab) {
  8302. state.bridgeSubTab = tab;
  8303. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8304. tabs.forEach(t => {
  8305. const panel = document.getElementById(`bridge-subtab-${t}`);
  8306. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8307. if (panel) {
  8308. if (t === tab) panel.classList.remove('hidden');
  8309. else panel.classList.add('hidden');
  8310. }
  8311. if (btn) {
  8312. if (t === tab) {
  8313. 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';
  8314. } else {
  8315. 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';
  8316. }
  8317. }
  8318. });
  8319. const addBtn = document.getElementById('bridge-top-action-btn');
  8320. if (addBtn) {
  8321. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8322. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8323. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8324. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8325. }
  8326. if (tab === 'hosts') loadBridgeHosts();
  8327. setTimeout(initTableSorting, 50);
  8328. }
  8329. function openCurrentBridgeModal() {
  8330. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8331. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8332. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8333. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8334. }
  8335. async function loadBridge() {
  8336. try {
  8337. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8338. fetch(`${API_BASE}/bridge/bridges`),
  8339. fetch(`${API_BASE}/bridge/ports`),
  8340. fetch(`${API_BASE}/bridge/vlans`),
  8341. fetch(`${API_BASE}/bridge/summary`),
  8342. fetch(`${API_BASE}/vpn/eoip`),
  8343. fetch(`${API_BASE}/vlans`)
  8344. ]);
  8345. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8346. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8347. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8348. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8349. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8350. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8351. // Badges & Stats
  8352. const bBridges = document.getElementById('bridge-badge-bridges');
  8353. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8354. const bPorts = document.getElementById('bridge-badge-ports');
  8355. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8356. const bVlans = document.getElementById('bridge-badge-vlans');
  8357. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8358. const bHosts = document.getElementById('bridge-badge-hosts');
  8359. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8360. const sBr = document.getElementById('bridge-stat-bridges');
  8361. if (sBr) sBr.innerText = (state.bridges || []).length;
  8362. const sPorts = document.getElementById('bridge-stat-ports');
  8363. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8364. const sHosts = document.getElementById('bridge-stat-hosts');
  8365. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8366. renderBridges();
  8367. renderBridgePorts();
  8368. renderBridgeVLANs();
  8369. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8370. } catch (err) {
  8371. console.error('Failed to load bridge subsystem:', err);
  8372. }
  8373. }
  8374. // ----------------- Bridges -----------------
  8375. function renderBridges() {
  8376. const tbody = document.getElementById('bridge-table-body');
  8377. const empty = document.getElementById('bridge-empty-bridges');
  8378. const countBadge = document.getElementById('bridge-count-badge');
  8379. if (!tbody) return;
  8380. tbody.innerHTML = '';
  8381. const bridges = state.bridges || [];
  8382. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8383. if (bridges.length === 0) {
  8384. empty?.classList.remove('hidden');
  8385. return;
  8386. }
  8387. empty?.classList.add('hidden');
  8388. bridges.forEach((b, idx) => {
  8389. const tr = document.createElement('tr');
  8390. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8391. // Format IP addresses pill list
  8392. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8393. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8394. ipsHtml = b.ip_addresses.map(ip => `
  8395. <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">
  8396. <span>${ip}</span>
  8397. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8398. </span>
  8399. `).join(' ');
  8400. }
  8401. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8402. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8403. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8404. tr.innerHTML = `
  8405. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8406. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8407. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8408. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8409. </td>
  8410. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8411. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8412. <td class="py-2.5 px-3">
  8413. <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>
  8414. </td>
  8415. <td class="py-2.5 px-3 text-center">
  8416. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8417. </td>
  8418. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8419. <td class="py-2.5 px-3">
  8420. <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>
  8421. </td>
  8422. <td class="py-2.5 px-3">
  8423. <div class="flex items-center gap-1.5 flex-wrap">
  8424. ${ipsHtml}
  8425. <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>
  8426. </div>
  8427. </td>
  8428. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8429. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8430. </td>
  8431. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8432. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8433. <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>
  8434. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8435. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8436. </td>
  8437. `;
  8438. tbody.appendChild(tr);
  8439. });
  8440. }
  8441. function openAddBridgeModal() {
  8442. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8443. document.getElementById('bridge-modal-id').value = '';
  8444. document.getElementById('bridge-modal-name').value = 'bridge1';
  8445. document.getElementById('bridge-modal-name').disabled = false;
  8446. document.getElementById('bridge-modal-mtu').value = '1500';
  8447. document.getElementById('bridge-modal-mac').value = '';
  8448. document.getElementById('bridge-modal-stp').value = 'rstp';
  8449. document.getElementById('bridge-modal-priority').value = '32768';
  8450. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8451. document.getElementById('bridge-modal-pvid').value = '1';
  8452. document.getElementById('bridge-modal-fastforward').checked = true;
  8453. document.getElementById('bridge-modal-comment').value = '';
  8454. document.getElementById('bridge-modal-disabled').checked = false;
  8455. toggleBridgeModalVlanFiltering();
  8456. document.getElementById('bridge-modal').classList.remove('hidden');
  8457. }
  8458. function openEditBridgeModal(id) {
  8459. const b = (state.bridges || []).find(x => x.id === id);
  8460. if (!b) return;
  8461. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8462. document.getElementById('bridge-modal-id').value = b.id;
  8463. document.getElementById('bridge-modal-name').value = b.name;
  8464. document.getElementById('bridge-modal-name').disabled = true;
  8465. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8466. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8467. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8468. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8469. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8470. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8471. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8472. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8473. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8474. toggleBridgeModalVlanFiltering();
  8475. document.getElementById('bridge-modal').classList.remove('hidden');
  8476. }
  8477. function closeBridgeModal() {
  8478. document.getElementById('bridge-modal').classList.add('hidden');
  8479. }
  8480. function toggleBridgeModalVlanFiltering() {
  8481. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8482. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8483. if (pvidBox) {
  8484. if (chk) pvidBox.classList.remove('opacity-40');
  8485. else pvidBox.classList.add('opacity-40');
  8486. }
  8487. }
  8488. async function submitSaveBridge(e) {
  8489. e.preventDefault();
  8490. const id = document.getElementById('bridge-modal-id').value;
  8491. const name = document.getElementById('bridge-modal-name').value.trim();
  8492. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8493. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8494. const stp = document.getElementById('bridge-modal-stp').value;
  8495. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8496. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8497. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8498. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8499. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8500. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8501. try {
  8502. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8503. method: 'POST',
  8504. headers: { 'Content-Type': 'application/json' },
  8505. body: JSON.stringify({
  8506. id,
  8507. name,
  8508. mtu,
  8509. mac_address: mac,
  8510. stp,
  8511. priority,
  8512. vlan_filtering: vlanFiltering,
  8513. pvid,
  8514. fast_forward: fastForward,
  8515. comment,
  8516. disabled
  8517. })
  8518. });
  8519. if (res.ok) {
  8520. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8521. closeBridgeModal();
  8522. loadBridge();
  8523. fetchData(false);
  8524. } else {
  8525. const err = await res.json();
  8526. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8527. }
  8528. } catch (err) {
  8529. showToast('Error', err.message, 'error');
  8530. }
  8531. }
  8532. async function toggleBridgeState(id, disabled) {
  8533. try {
  8534. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8535. method: 'POST',
  8536. headers: { 'Content-Type': 'application/json' },
  8537. body: JSON.stringify({ disabled })
  8538. });
  8539. if (res.ok) {
  8540. loadBridge();
  8541. fetchData(false);
  8542. }
  8543. } catch (err) {
  8544. showToast('Error', err.message, 'error');
  8545. }
  8546. }
  8547. async function deleteBridge(id) {
  8548. const b = (state.bridges || []).find(x => x.id === id);
  8549. const name = b ? b.name : id;
  8550. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8551. try {
  8552. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8553. if (res.ok) {
  8554. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8555. loadBridge();
  8556. fetchData(false);
  8557. } else {
  8558. const err = await res.json();
  8559. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8560. }
  8561. } catch (err) {
  8562. showToast('Error', err.message, 'error');
  8563. }
  8564. }
  8565. // ----------------- Bridge IP Assignments -----------------
  8566. function openAddBridgeIPModal(id, name) {
  8567. document.getElementById('bridge-ip-modal-id').value = id;
  8568. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8569. document.getElementById('bridge-ip-modal-cidr').value = '';
  8570. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8571. }
  8572. function closeBridgeIPModal() {
  8573. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8574. }
  8575. async function submitAddBridgeIP(e) {
  8576. e.preventDefault();
  8577. const id = document.getElementById('bridge-ip-modal-id').value;
  8578. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8579. try {
  8580. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8581. method: 'POST',
  8582. headers: { 'Content-Type': 'application/json' },
  8583. body: JSON.stringify({ ip })
  8584. });
  8585. if (res.ok) {
  8586. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8587. closeBridgeIPModal();
  8588. loadBridge();
  8589. fetchData(false);
  8590. } else {
  8591. const err = await res.json();
  8592. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8593. }
  8594. } catch (err) {
  8595. showToast('Error', err.message, 'error');
  8596. }
  8597. }
  8598. async function deleteBridgeIP(id, ip) {
  8599. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8600. try {
  8601. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8602. method: 'DELETE',
  8603. headers: { 'Content-Type': 'application/json' },
  8604. body: JSON.stringify({ ip })
  8605. });
  8606. if (res.ok) {
  8607. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8608. loadBridge();
  8609. fetchData(false);
  8610. }
  8611. } catch (err) {
  8612. showToast('Error', err.message, 'error');
  8613. }
  8614. }
  8615. // ----------------- Bridge Ports -----------------
  8616. function renderBridgePorts() {
  8617. const tbody = document.getElementById('bridge-ports-table-body');
  8618. const empty = document.getElementById('bridge-empty-ports');
  8619. const countBadge = document.getElementById('bridge-ports-count-badge');
  8620. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8621. if (!tbody) return;
  8622. tbody.innerHTML = '';
  8623. // Update filter select
  8624. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8625. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8626. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8627. if (ports.length === 0) {
  8628. empty?.classList.remove('hidden');
  8629. return;
  8630. }
  8631. empty?.classList.add('hidden');
  8632. ports.forEach((p, idx) => {
  8633. const tr = document.createElement('tr');
  8634. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8635. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8636. tr.innerHTML = `
  8637. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8638. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8639. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8640. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8641. </td>
  8642. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8643. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8644. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8645. <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>
  8646. <td class="py-2.5 px-3">
  8647. ${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>'}
  8648. </td>
  8649. <td class="py-2.5 px-3">
  8650. <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>
  8651. </td>
  8652. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8653. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8654. <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>
  8655. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8656. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8657. </td>
  8658. `;
  8659. tbody.appendChild(tr);
  8660. });
  8661. }
  8662. function openAddBridgePortModal() {
  8663. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8664. document.getElementById('bridge-port-modal-id').value = '';
  8665. populateBridgeSelect('bridge-port-modal-bridge');
  8666. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8667. document.getElementById('bridge-port-modal-pvid').value = '1';
  8668. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8669. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8670. document.getElementById('bridge-port-modal-horizon').value = '0';
  8671. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8672. document.getElementById('bridge-port-modal-priority').value = '128';
  8673. document.getElementById('bridge-port-modal-learn').checked = true;
  8674. document.getElementById('bridge-port-modal-comment').value = '';
  8675. document.getElementById('bridge-port-modal-disabled').checked = false;
  8676. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8677. }
  8678. function openEditBridgePortModal(id) {
  8679. const p = (state.bridgePorts || []).find(x => x.id === id);
  8680. if (!p) return;
  8681. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8682. document.getElementById('bridge-port-modal-id').value = p.id;
  8683. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8684. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8685. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8686. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8687. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8688. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8689. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8690. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8691. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8692. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8693. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8694. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8695. }
  8696. function closeBridgePortModal() {
  8697. document.getElementById('bridge-port-modal').classList.add('hidden');
  8698. }
  8699. async function submitSaveBridgePort(e) {
  8700. e.preventDefault();
  8701. const id = document.getElementById('bridge-port-modal-id').value;
  8702. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8703. const iface = document.getElementById('bridge-port-modal-interface').value;
  8704. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8705. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8706. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8707. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8708. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8709. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8710. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8711. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8712. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8713. try {
  8714. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8715. method: 'POST',
  8716. headers: { 'Content-Type': 'application/json' },
  8717. body: JSON.stringify({
  8718. id,
  8719. bridge,
  8720. interface: iface,
  8721. pvid,
  8722. frame_types: frameTypes,
  8723. ingress_filtering: ingressFiltering,
  8724. horizon,
  8725. path_cost: pathCost,
  8726. priority,
  8727. learn,
  8728. comment,
  8729. disabled
  8730. })
  8731. });
  8732. if (res.ok) {
  8733. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8734. closeBridgePortModal();
  8735. loadBridge();
  8736. fetchData(false);
  8737. } else {
  8738. const err = await res.json();
  8739. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8740. }
  8741. } catch (err) {
  8742. showToast('Error', err.message, 'error');
  8743. }
  8744. }
  8745. async function toggleBridgePortState(id, disabled) {
  8746. try {
  8747. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8748. method: 'POST',
  8749. headers: { 'Content-Type': 'application/json' },
  8750. body: JSON.stringify({ disabled })
  8751. });
  8752. if (res.ok) {
  8753. loadBridge();
  8754. fetchData(false);
  8755. }
  8756. } catch (err) {
  8757. showToast('Error', err.message, 'error');
  8758. }
  8759. }
  8760. async function deleteBridgePort(id) {
  8761. const p = (state.bridgePorts || []).find(x => x.id === id);
  8762. const iface = p ? p.interface : id;
  8763. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8764. try {
  8765. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8766. if (res.ok) {
  8767. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8768. loadBridge();
  8769. fetchData(false);
  8770. }
  8771. } catch (err) {
  8772. showToast('Error', err.message, 'error');
  8773. }
  8774. }
  8775. // ----------------- Bridge VLANs -----------------
  8776. function renderBridgeVLANs() {
  8777. const tbody = document.getElementById('bridge-vlans-table-body');
  8778. const empty = document.getElementById('bridge-empty-vlans');
  8779. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8780. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8781. if (!tbody) return;
  8782. tbody.innerHTML = '';
  8783. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8784. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8785. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8786. if (vlans.length === 0) {
  8787. empty?.classList.remove('hidden');
  8788. return;
  8789. }
  8790. empty?.classList.add('hidden');
  8791. vlans.forEach((v, idx) => {
  8792. const tr = document.createElement('tr');
  8793. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8794. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8795. ? 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(' ')
  8796. : '<span class="text-slate-600">none</span>';
  8797. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8798. ? 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(' ')
  8799. : '<span class="text-slate-600">none</span>';
  8800. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8801. tr.innerHTML = `
  8802. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8803. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8804. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8805. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8806. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8807. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8808. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8809. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8810. <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>
  8811. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8812. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8813. </td>
  8814. `;
  8815. tbody.appendChild(tr);
  8816. });
  8817. }
  8818. function openAddBridgeVLANModal() {
  8819. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8820. document.getElementById('bridge-vlan-modal-id').value = '';
  8821. populateBridgeSelect('bridge-vlan-modal-bridge');
  8822. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8823. document.getElementById('bridge-vlan-modal-comment').value = '';
  8824. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8825. updateBridgeVlanPortCheckboxes();
  8826. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8827. }
  8828. function openEditBridgeVLANModal(id) {
  8829. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8830. if (!v) return;
  8831. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8832. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8833. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8834. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8835. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8836. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8837. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8838. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8839. }
  8840. function closeBridgeVlanModal() {
  8841. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8842. }
  8843. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8844. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8845. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8846. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8847. if (!taggedBox || !untaggedBox) return;
  8848. // Ports belonging to the selected bridge
  8849. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8850. if (memberPorts.length === 0) {
  8851. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8852. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8853. return;
  8854. }
  8855. taggedBox.innerHTML = memberPorts.map(p => `
  8856. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8857. <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">
  8858. <span>${p.interface}</span>
  8859. </label>
  8860. `).join('');
  8861. untaggedBox.innerHTML = memberPorts.map(p => `
  8862. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8863. <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">
  8864. <span>${p.interface}</span>
  8865. </label>
  8866. `).join('');
  8867. }
  8868. async function submitSaveBridgeVLAN(e) {
  8869. e.preventDefault();
  8870. const id = document.getElementById('bridge-vlan-modal-id').value;
  8871. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8872. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8873. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8874. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8875. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8876. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8877. try {
  8878. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8879. method: 'POST',
  8880. headers: { 'Content-Type': 'application/json' },
  8881. body: JSON.stringify({
  8882. id,
  8883. bridge,
  8884. vlan_ids: vlanIDs,
  8885. tagged,
  8886. untagged,
  8887. comment,
  8888. disabled
  8889. })
  8890. });
  8891. if (res.ok) {
  8892. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8893. closeBridgeVlanModal();
  8894. loadBridge();
  8895. } else {
  8896. const err = await res.json();
  8897. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8898. }
  8899. } catch (err) {
  8900. showToast('Error', err.message, 'error');
  8901. }
  8902. }
  8903. async function toggleBridgeVLANState(id, disabled) {
  8904. try {
  8905. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8906. method: 'POST',
  8907. headers: { 'Content-Type': 'application/json' },
  8908. body: JSON.stringify({ disabled })
  8909. });
  8910. if (res.ok) loadBridge();
  8911. } catch (err) {
  8912. showToast('Error', err.message, 'error');
  8913. }
  8914. }
  8915. async function deleteBridgeVLAN(id) {
  8916. if (!confirm('Delete this bridge VLAN entry?')) return;
  8917. try {
  8918. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8919. if (res.ok) {
  8920. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  8921. loadBridge();
  8922. }
  8923. } catch (err) {
  8924. showToast('Error', err.message, 'error');
  8925. }
  8926. }
  8927. // ----------------- Hosts / MAC Table -----------------
  8928. async function loadBridgeHosts() {
  8929. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  8930. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  8931. try {
  8932. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  8933. const res = await fetch(url);
  8934. if (res.ok) {
  8935. state.bridgeHosts = await res.json();
  8936. renderBridgeHosts();
  8937. }
  8938. } catch (err) {
  8939. console.error('Failed to load bridge hosts:', err);
  8940. }
  8941. }
  8942. function renderBridgeHosts() {
  8943. const tbody = document.getElementById('bridge-hosts-table-body');
  8944. const empty = document.getElementById('bridge-empty-hosts');
  8945. const countBadge = document.getElementById('bridge-hosts-count-badge');
  8946. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  8947. if (!tbody) return;
  8948. tbody.innerHTML = '';
  8949. const hosts = (state.bridgeHosts || []).filter(h => {
  8950. if (!search) return true;
  8951. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  8952. });
  8953. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  8954. if (hosts.length === 0) {
  8955. empty?.classList.remove('hidden');
  8956. return;
  8957. }
  8958. empty?.classList.add('hidden');
  8959. hosts.forEach(h => {
  8960. const tr = document.createElement('tr');
  8961. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  8962. let flagBadges = '';
  8963. 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>';
  8964. 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>';
  8965. 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>';
  8966. tr.innerHTML = `
  8967. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  8968. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  8969. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  8970. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  8971. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  8972. <td class="py-2.5 px-3">${flagBadges}</td>
  8973. `;
  8974. tbody.appendChild(tr);
  8975. });
  8976. }
  8977. async function flushBridgeHosts() {
  8978. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  8979. if (!selBridge) {
  8980. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  8981. return;
  8982. }
  8983. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  8984. try {
  8985. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  8986. method: 'POST',
  8987. headers: { 'Content-Type': 'application/json' },
  8988. body: JSON.stringify({ bridge: selBridge })
  8989. });
  8990. if (res.ok) {
  8991. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  8992. loadBridgeHosts();
  8993. }
  8994. } catch (err) {
  8995. showToast('Error', err.message, 'error');
  8996. }
  8997. }
  8998. // ----------------- Helpers -----------------
  8999. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9000. const sel = document.getElementById(selectId);
  9001. if (!sel) return;
  9002. const prevVal = currentVal || sel.value;
  9003. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9004. (state.bridges || []).forEach(b => {
  9005. const opt = document.createElement('option');
  9006. opt.value = b.name;
  9007. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9008. if (b.name === prevVal) opt.selected = true;
  9009. sel.appendChild(opt);
  9010. });
  9011. }
  9012. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9013. const sel = document.getElementById(selectId);
  9014. if (!sel) return;
  9015. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9016. // 1. Physical Interfaces
  9017. const grpPhys = document.createElement('optgroup');
  9018. grpPhys.label = 'Physical Interfaces';
  9019. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9020. const opt = document.createElement('option');
  9021. opt.value = i.name;
  9022. opt.innerText = `${i.name} (${i.role || i.type})`;
  9023. if (i.name === currentVal) opt.selected = true;
  9024. grpPhys.appendChild(opt);
  9025. });
  9026. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9027. // 2. VLAN Sub-interfaces
  9028. const grpVlans = document.createElement('optgroup');
  9029. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9030. (state.vlans || []).forEach(v => {
  9031. const opt = document.createElement('option');
  9032. opt.value = v.name;
  9033. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9034. if (v.name === currentVal) opt.selected = true;
  9035. grpVlans.appendChild(opt);
  9036. });
  9037. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9038. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9039. const grpEoip = document.createElement('optgroup');
  9040. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9041. (state.eoipTunnels || []).forEach(t => {
  9042. const opt = document.createElement('option');
  9043. opt.value = t.name;
  9044. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9045. if (t.name === currentVal) opt.selected = true;
  9046. grpEoip.appendChild(opt);
  9047. });
  9048. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9049. }
  9050. // -------------------------------------------------------------
  9051. // RouterOS v7 Routing Filters Management (/routing filter)
  9052. // -------------------------------------------------------------
  9053. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9054. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9055. if (!state.rfSort) state.rfSort = {};
  9056. function switchRoutingFilterTab(tab) {
  9057. state.activeRoutingFilterTab = tab;
  9058. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9059. tabs.forEach(t => {
  9060. const btn = document.getElementById(`tab-rf-${t}`);
  9061. const content = document.getElementById(`tab-content-rf-${t}`);
  9062. if (btn) {
  9063. if (t === tab) {
  9064. 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';
  9065. } else {
  9066. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9067. }
  9068. }
  9069. if (content) {
  9070. if (t === tab) content.classList.remove('hidden');
  9071. else content.classList.add('hidden');
  9072. }
  9073. });
  9074. const chainContainer = document.getElementById('rf-chain-filter-container');
  9075. if (chainContainer) {
  9076. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9077. else chainContainer.classList.add('hidden');
  9078. }
  9079. renderRoutingFilters();
  9080. }
  9081. function selectFilterRow(tab, id) {
  9082. if (state.selectedFilterRow[tab] === id) {
  9083. delete state.selectedFilterRow[tab];
  9084. } else {
  9085. state.selectedFilterRow[tab] = id;
  9086. }
  9087. if (tab === 'rules') renderRoutingFilterRules();
  9088. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9089. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9090. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9091. }
  9092. function openRoutingFilterNewModal() {
  9093. const tab = state.activeRoutingFilterTab || 'rules';
  9094. if (tab === 'rules') openAddRoutingFilterModal();
  9095. else if (tab === 'select-rules') openAddSelectRuleModal();
  9096. else if (tab === 'community-lists') openAddCommunityListModal();
  9097. else if (tab === 'as-lists') openAddASListModal();
  9098. }
  9099. function toggleSelectedRoutingFilter(disabled) {
  9100. const tab = state.activeRoutingFilterTab || 'rules';
  9101. const id = state.selectedFilterRow[tab];
  9102. if (!id) {
  9103. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9104. return;
  9105. }
  9106. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9107. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9108. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9109. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9110. }
  9111. function removeSelectedRoutingFilter() {
  9112. const tab = state.activeRoutingFilterTab || 'rules';
  9113. const id = state.selectedFilterRow[tab];
  9114. if (!id) {
  9115. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9116. return;
  9117. }
  9118. if (tab === 'rules') deleteRoutingFilter(id);
  9119. else if (tab === 'select-rules') deleteSelectRule(id);
  9120. else if (tab === 'community-lists') deleteCommunityList(id);
  9121. else if (tab === 'as-lists') deleteASList(id);
  9122. }
  9123. function searchRoutingFilters(q) {
  9124. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9125. renderRoutingFilters();
  9126. }
  9127. function sortFilterTable(tab, col) {
  9128. if (!state.rfSort) state.rfSort = {};
  9129. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9130. if (state.rfSort[tab].col === col) {
  9131. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9132. } else {
  9133. state.rfSort[tab].col = col;
  9134. state.rfSort[tab].asc = true;
  9135. }
  9136. const asc = state.rfSort[tab].asc;
  9137. let list = [];
  9138. if (tab === 'rules') list = state.routingFilters || [];
  9139. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9140. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9141. else if (tab === 'as-lists') list = state.routingASLists || [];
  9142. list.sort((a, b) => {
  9143. let valA = a[col] ?? '';
  9144. let valB = b[col] ?? '';
  9145. if (col === 'flags') {
  9146. valA = a.disabled ? 'X' : 'A';
  9147. valB = b.disabled ? 'X' : 'A';
  9148. }
  9149. if (typeof valA === 'number' && typeof valB === 'number') {
  9150. return asc ? valA - valB : valB - valA;
  9151. }
  9152. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9153. });
  9154. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9155. allCols.forEach(c => {
  9156. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9157. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9158. });
  9159. if (tab === 'rules') renderRoutingFilterRules();
  9160. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9161. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9162. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9163. }
  9164. function renderRoutingFilters() {
  9165. const navBadge = document.getElementById('badge-filters-count');
  9166. const allRules = state.routingFilters || [];
  9167. if (navBadge) navBadge.innerText = allRules.length;
  9168. // Populate chain filter select options and datalist
  9169. const chainSelect = document.getElementById('routing-filter-chain-select');
  9170. const chainDatalist = document.getElementById('dl-routing-chains');
  9171. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9172. if (chainSelect) {
  9173. const currentVal = state.filterChainSelected || 'all';
  9174. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9175. uniqueChains.map(ch => {
  9176. const count = allRules.filter(r => r.chain === ch).length;
  9177. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9178. }).join('');
  9179. chainSelect.value = currentVal;
  9180. }
  9181. if (chainDatalist) {
  9182. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9183. }
  9184. renderRoutingFilterRules();
  9185. renderRoutingFilterSelectRules();
  9186. renderRoutingFilterCommunityLists();
  9187. renderRoutingFilterASLists();
  9188. }
  9189. function filterRoutingFiltersByChain(chain) {
  9190. state.filterChainSelected = chain;
  9191. renderRoutingFilters();
  9192. }
  9193. // -------------------------------------------------------------
  9194. // TAB 1: RULES (/routing filter rule)
  9195. // -------------------------------------------------------------
  9196. function renderRoutingFilterRules() {
  9197. const tbody = document.getElementById('routing-filter-rules-tbody');
  9198. if (!tbody) return;
  9199. const empty = document.getElementById('rf-rules-empty');
  9200. const statusCount = document.getElementById('rf-status-count');
  9201. let list = (state.routingFilters || []).slice();
  9202. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9203. list = list.filter(r => r.chain === state.filterChainSelected);
  9204. }
  9205. const q = state.rfSearchQuery;
  9206. if (q) {
  9207. list = list.filter(r =>
  9208. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9209. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9210. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9211. (r.comment && r.comment.toLowerCase().includes(q))
  9212. );
  9213. }
  9214. if (!state.rfSort?.['rules']) {
  9215. list.sort((a, b) => {
  9216. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9217. return (a.rule_order || 0) - (b.rule_order || 0);
  9218. });
  9219. }
  9220. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9221. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9222. }
  9223. if (list.length === 0) {
  9224. tbody.innerHTML = '';
  9225. if (empty) empty.classList.remove('hidden');
  9226. return;
  9227. }
  9228. if (empty) empty.classList.add('hidden');
  9229. tbody.innerHTML = list.map(r => {
  9230. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9231. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9232. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9233. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9234. let ruleDisplay = '';
  9235. if (r.rule && r.rule.trim() !== '') {
  9236. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9237. } else {
  9238. let conds = [];
  9239. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9240. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9241. let act = r.action || 'accept';
  9242. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9243. }
  9244. return `
  9245. <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'}">
  9246. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9247. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9248. <td class="py-2 px-3">
  9249. <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>
  9250. </td>
  9251. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9252. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9253. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9254. <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>
  9255. <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>
  9256. <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'}">
  9257. ${r.disabled ? 'Enable' : 'Disable'}
  9258. </button>
  9259. <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">
  9260. Edit
  9261. </button>
  9262. <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">
  9263. ✕
  9264. </button>
  9265. </td>
  9266. </tr>
  9267. `;
  9268. }).join('');
  9269. }
  9270. // -------------------------------------------------------------
  9271. // TAB 2: SELECT RULES (/routing filter select-rule)
  9272. // -------------------------------------------------------------
  9273. function renderRoutingFilterSelectRules() {
  9274. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9275. if (!tbody) return;
  9276. const empty = document.getElementById('rf-select-rules-empty');
  9277. const statusCount = document.getElementById('rf-status-count');
  9278. let list = (state.routingSelectRules || []).slice();
  9279. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9280. list = list.filter(r => r.chain === state.filterChainSelected);
  9281. }
  9282. const q = state.rfSearchQuery;
  9283. if (q) {
  9284. list = list.filter(r =>
  9285. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9286. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9287. (r.comment && r.comment.toLowerCase().includes(q))
  9288. );
  9289. }
  9290. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9291. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9292. }
  9293. if (list.length === 0) {
  9294. tbody.innerHTML = '';
  9295. if (empty) empty.classList.remove('hidden');
  9296. return;
  9297. }
  9298. if (empty) empty.classList.add('hidden');
  9299. tbody.innerHTML = list.map(r => {
  9300. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9301. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9302. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9303. return `
  9304. <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'}">
  9305. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9306. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9307. <td class="py-2 px-3">
  9308. <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>
  9309. </td>
  9310. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9311. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9312. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9313. <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'}">
  9314. ${r.disabled ? 'Enable' : 'Disable'}
  9315. </button>
  9316. <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">
  9317. Edit
  9318. </button>
  9319. <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">
  9320. ✕
  9321. </button>
  9322. </td>
  9323. </tr>
  9324. `;
  9325. }).join('');
  9326. }
  9327. // -------------------------------------------------------------
  9328. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9329. // -------------------------------------------------------------
  9330. function renderRoutingFilterCommunityLists() {
  9331. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9332. if (!tbody) return;
  9333. const empty = document.getElementById('rf-comm-lists-empty');
  9334. const statusCount = document.getElementById('rf-status-count');
  9335. let list = (state.routingCommunityLists || []).slice();
  9336. const q = state.rfSearchQuery;
  9337. if (q) {
  9338. list = list.filter(cl =>
  9339. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9340. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9341. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9342. );
  9343. }
  9344. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9345. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9346. }
  9347. if (list.length === 0) {
  9348. tbody.innerHTML = '';
  9349. if (empty) empty.classList.remove('hidden');
  9350. return;
  9351. }
  9352. if (empty) empty.classList.add('hidden');
  9353. tbody.innerHTML = list.map(cl => {
  9354. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9355. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9356. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9357. const commBadges = (cl.communities || []).map(c =>
  9358. `<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>`
  9359. ).join(' ');
  9360. return `
  9361. <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'}">
  9362. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9363. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9364. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9365. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9366. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9367. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9368. <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'}">
  9369. ${cl.disabled ? 'Enable' : 'Disable'}
  9370. </button>
  9371. <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">
  9372. Edit
  9373. </button>
  9374. <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">
  9375. ✕
  9376. </button>
  9377. </td>
  9378. </tr>
  9379. `;
  9380. }).join('');
  9381. }
  9382. // -------------------------------------------------------------
  9383. // TAB 4: AS LISTS (/routing filter num-list)
  9384. // -------------------------------------------------------------
  9385. function renderRoutingFilterASLists() {
  9386. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9387. if (!tbody) return;
  9388. const empty = document.getElementById('rf-as-lists-empty');
  9389. const statusCount = document.getElementById('rf-status-count');
  9390. let list = (state.routingASLists || []).slice();
  9391. const q = state.rfSearchQuery;
  9392. if (q) {
  9393. list = list.filter(al =>
  9394. (al.name && al.name.toLowerCase().includes(q)) ||
  9395. (al.range && al.range.toLowerCase().includes(q)) ||
  9396. (al.comment && al.comment.toLowerCase().includes(q))
  9397. );
  9398. }
  9399. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9400. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9401. }
  9402. if (list.length === 0) {
  9403. tbody.innerHTML = '';
  9404. if (empty) empty.classList.remove('hidden');
  9405. return;
  9406. }
  9407. if (empty) empty.classList.add('hidden');
  9408. tbody.innerHTML = list.map(al => {
  9409. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9410. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9411. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9412. return `
  9413. <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'}">
  9414. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9415. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9416. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9417. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9418. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9419. <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'}">
  9420. ${al.disabled ? 'Enable' : 'Disable'}
  9421. </button>
  9422. <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">
  9423. Edit
  9424. </button>
  9425. <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">
  9426. ✕
  9427. </button>
  9428. </td>
  9429. </tr>
  9430. `;
  9431. }).join('');
  9432. }
  9433. // -------------------------------------------------------------
  9434. // SNIPPETS & WIZARD HELPERS
  9435. // -------------------------------------------------------------
  9436. function insertRuleSnippet(type) {
  9437. const textarea = document.getElementById('modal-rf-rule');
  9438. if (!textarea) return;
  9439. let snippet = '';
  9440. switch (type) {
  9441. case 'accept-default':
  9442. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9443. break;
  9444. case 'drop-rfc1918':
  9445. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9446. break;
  9447. case 'len-24':
  9448. snippet = 'if (dst-len > 24) { reject; }';
  9449. break;
  9450. case 'local-pref-150':
  9451. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9452. break;
  9453. case 'as-prepend-2':
  9454. snippet = 'set bgp-path-prepend 2; accept;';
  9455. break;
  9456. case 'set-comm':
  9457. snippet = 'set bgp-communities.add 65000:100; accept;';
  9458. break;
  9459. case 'match-comm':
  9460. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9461. break;
  9462. case 'reject-all':
  9463. snippet = 'reject;';
  9464. break;
  9465. }
  9466. if (!snippet) return;
  9467. if (!textarea.value.trim()) {
  9468. textarea.value = snippet;
  9469. } else {
  9470. textarea.value = textarea.value.trim() + '\n' + snippet;
  9471. }
  9472. }
  9473. function generateScriptFromWizard() {
  9474. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9475. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9476. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9477. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9478. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9479. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9480. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9481. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9482. const conds = [];
  9483. if (pfx) {
  9484. if (pfxLen) {
  9485. if (pfxLen.includes('-')) {
  9486. const parts = pfxLen.split('-');
  9487. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9488. } else {
  9489. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9490. }
  9491. } else {
  9492. conds.push(`dst in ${pfx}`);
  9493. }
  9494. }
  9495. if (proto && proto !== 'any') {
  9496. conds.push(`protocol ${proto}`);
  9497. }
  9498. if (asp) {
  9499. conds.push(`bgp-as-path "${asp}"`);
  9500. }
  9501. if (comm) {
  9502. conds.push(`bgp-communities includes ${comm}`);
  9503. }
  9504. const actions = [];
  9505. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9506. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9507. actions.push(`${act};`);
  9508. let code = '';
  9509. if (conds.length > 0) {
  9510. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9511. } else {
  9512. code = actions.join(' ');
  9513. }
  9514. const textarea = document.getElementById('modal-rf-rule');
  9515. if (textarea) textarea.value = code;
  9516. }
  9517. // -------------------------------------------------------------
  9518. // MODAL CRUD: RULES (/routing filter rule)
  9519. // -------------------------------------------------------------
  9520. function openAddRoutingFilterModal(defaultChain = '') {
  9521. const form = document.getElementById('routing-filter-form');
  9522. if (form) form.reset();
  9523. const idEl = document.getElementById('modal-rf-id');
  9524. if (idEl) idEl.value = '';
  9525. const titleEl = document.getElementById('modal-rf-title');
  9526. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9527. const chainEl = document.getElementById('modal-rf-chain');
  9528. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9529. const orderEl = document.getElementById('modal-rf-order');
  9530. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9531. const ruleEl = document.getElementById('modal-rf-rule');
  9532. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9533. const disEl = document.getElementById('modal-rf-disabled');
  9534. if (disEl) disEl.checked = false;
  9535. const modal = document.getElementById('modal-routing-filter');
  9536. if (modal) modal.classList.remove('hidden');
  9537. }
  9538. function openEditRoutingFilterModal(id) {
  9539. const r = (state.routingFilters || []).find(item => item.id === id);
  9540. if (!r) return;
  9541. const idEl = document.getElementById('modal-rf-id');
  9542. if (idEl) idEl.value = r.id;
  9543. const titleEl = document.getElementById('modal-rf-title');
  9544. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9545. const chainEl = document.getElementById('modal-rf-chain');
  9546. if (chainEl) chainEl.value = r.chain || '';
  9547. const orderEl = document.getElementById('modal-rf-order');
  9548. if (orderEl) orderEl.value = r.rule_order || 10;
  9549. const ruleEl = document.getElementById('modal-rf-rule');
  9550. if (ruleEl) {
  9551. if (r.rule) {
  9552. ruleEl.value = r.rule;
  9553. } else {
  9554. let conds = [];
  9555. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9556. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9557. let act = r.action || 'accept';
  9558. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9559. }
  9560. }
  9561. const comEl = document.getElementById('modal-rf-comment');
  9562. if (comEl) comEl.value = r.comment || '';
  9563. const disEl = document.getElementById('modal-rf-disabled');
  9564. if (disEl) disEl.checked = !!r.disabled;
  9565. const modal = document.getElementById('modal-routing-filter');
  9566. if (modal) modal.classList.remove('hidden');
  9567. }
  9568. function closeRoutingFilterModal() {
  9569. const modal = document.getElementById('modal-routing-filter');
  9570. if (modal) modal.classList.add('hidden');
  9571. }
  9572. async function submitRoutingFilter(e) {
  9573. if (e) e.preventDefault();
  9574. const payload = {
  9575. id: document.getElementById('modal-rf-id').value,
  9576. chain: document.getElementById('modal-rf-chain').value.trim(),
  9577. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9578. rule: document.getElementById('modal-rf-rule').value.trim(),
  9579. comment: document.getElementById('modal-rf-comment').value.trim(),
  9580. disabled: document.getElementById('modal-rf-disabled').checked
  9581. };
  9582. try {
  9583. const res = await fetch(`${API_BASE}/routing/filters`, {
  9584. method: 'POST',
  9585. headers: { 'Content-Type': 'application/json' },
  9586. body: JSON.stringify(payload)
  9587. });
  9588. if (res.ok) {
  9589. closeRoutingFilterModal();
  9590. showToast('Success', 'Routing filter rule saved', 'success');
  9591. loadDynamicRouting();
  9592. } else {
  9593. const err = await res.json();
  9594. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9595. }
  9596. } catch (err) {
  9597. showToast('Error', err.message, 'error');
  9598. }
  9599. }
  9600. async function applyRoutingFilterForm() {
  9601. const payload = {
  9602. id: document.getElementById('modal-rf-id').value,
  9603. chain: document.getElementById('modal-rf-chain').value.trim(),
  9604. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9605. rule: document.getElementById('modal-rf-rule').value.trim(),
  9606. comment: document.getElementById('modal-rf-comment').value.trim(),
  9607. disabled: document.getElementById('modal-rf-disabled').checked
  9608. };
  9609. try {
  9610. const res = await fetch(`${API_BASE}/routing/filters`, {
  9611. method: 'POST',
  9612. headers: { 'Content-Type': 'application/json' },
  9613. body: JSON.stringify(payload)
  9614. });
  9615. if (res.ok) {
  9616. const data = await res.json();
  9617. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9618. showToast('Applied', 'Routing filter configuration applied', 'success');
  9619. loadDynamicRouting();
  9620. } else {
  9621. const err = await res.json();
  9622. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9623. }
  9624. } catch (err) {
  9625. showToast('Error', err.message, 'error');
  9626. }
  9627. }
  9628. async function moveRoutingFilterOrder(id, delta) {
  9629. const list = state.routingFilters || [];
  9630. const idx = list.findIndex(r => r.id === id);
  9631. if (idx < 0) return;
  9632. const targetIdx = idx + delta;
  9633. if (targetIdx < 0 || targetIdx >= list.length) return;
  9634. const currentOrder = list[idx].rule_order || 10;
  9635. const targetOrder = list[targetIdx].rule_order || 20;
  9636. list[idx].rule_order = targetOrder;
  9637. list[targetIdx].rule_order = currentOrder;
  9638. try {
  9639. await fetch(`${API_BASE}/routing/filters`, {
  9640. method: 'POST',
  9641. headers: { 'Content-Type': 'application/json' },
  9642. body: JSON.stringify(list[idx])
  9643. });
  9644. await fetch(`${API_BASE}/routing/filters`, {
  9645. method: 'POST',
  9646. headers: { 'Content-Type': 'application/json' },
  9647. body: JSON.stringify(list[targetIdx])
  9648. });
  9649. loadDynamicRouting();
  9650. } catch (e) {
  9651. console.error('Reorder error:', e);
  9652. }
  9653. }
  9654. async function deleteRoutingFilter(id) {
  9655. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  9656. try {
  9657. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9658. if (res.ok) {
  9659. showToast('Deleted', 'Routing filter rule removed', 'info');
  9660. loadDynamicRouting();
  9661. } else {
  9662. const err = await res.json();
  9663. showToast('Error', err.error || 'Failed to delete rule', 'error');
  9664. }
  9665. } catch (err) {
  9666. showToast('Error', err.message, 'error');
  9667. }
  9668. }
  9669. async function toggleRoutingFilterState(id, disabled) {
  9670. try {
  9671. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  9672. method: 'POST',
  9673. headers: { 'Content-Type': 'application/json' },
  9674. body: JSON.stringify({ disabled })
  9675. });
  9676. if (res.ok) {
  9677. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9678. loadDynamicRouting();
  9679. } else {
  9680. const err = await res.json();
  9681. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  9682. }
  9683. } catch (err) {
  9684. showToast('Error', err.message, 'error');
  9685. }
  9686. }
  9687. // -------------------------------------------------------------
  9688. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  9689. // -------------------------------------------------------------
  9690. function openAddSelectRuleModal() {
  9691. document.getElementById('modal-rf-sr-id').value = '';
  9692. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  9693. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  9694. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  9695. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  9696. document.getElementById('modal-rf-sr-comment').value = '';
  9697. document.getElementById('modal-rf-sr-disabled').checked = false;
  9698. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9699. }
  9700. function openEditSelectRuleModal(id) {
  9701. const r = (state.routingSelectRules || []).find(item => item.id === id);
  9702. if (!r) return;
  9703. document.getElementById('modal-rf-sr-id').value = r.id;
  9704. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  9705. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  9706. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  9707. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  9708. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  9709. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  9710. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9711. }
  9712. function closeSelectRuleModal() {
  9713. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  9714. }
  9715. async function submitSelectRule(e) {
  9716. e.preventDefault();
  9717. const payload = {
  9718. id: document.getElementById('modal-rf-sr-id').value,
  9719. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  9720. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  9721. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  9722. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  9723. disabled: document.getElementById('modal-rf-sr-disabled').checked
  9724. };
  9725. try {
  9726. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  9727. method: 'POST',
  9728. headers: { 'Content-Type': 'application/json' },
  9729. body: JSON.stringify(payload)
  9730. });
  9731. if (res.ok) {
  9732. closeSelectRuleModal();
  9733. showToast('Success', 'Select rule saved', 'success');
  9734. loadDynamicRouting();
  9735. } else {
  9736. const err = await res.json();
  9737. showToast('Error', err.error || 'Failed to save select rule', 'error');
  9738. }
  9739. } catch (err) {
  9740. showToast('Error', err.message, 'error');
  9741. }
  9742. }
  9743. async function deleteSelectRule(id) {
  9744. if (!confirm('Are you sure you want to delete this select rule?')) return;
  9745. try {
  9746. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9747. if (res.ok) {
  9748. showToast('Deleted', 'Select rule removed', 'info');
  9749. loadDynamicRouting();
  9750. } else {
  9751. const err = await res.json();
  9752. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  9753. }
  9754. } catch (err) {
  9755. showToast('Error', err.message, 'error');
  9756. }
  9757. }
  9758. async function toggleSelectRuleState(id, disabled) {
  9759. try {
  9760. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  9761. method: 'POST',
  9762. headers: { 'Content-Type': 'application/json' },
  9763. body: JSON.stringify({ disabled })
  9764. });
  9765. if (res.ok) {
  9766. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9767. loadDynamicRouting();
  9768. } else {
  9769. const err = await res.json();
  9770. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  9771. }
  9772. } catch (err) {
  9773. showToast('Error', err.message, 'error');
  9774. }
  9775. }
  9776. // -------------------------------------------------------------
  9777. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  9778. // -------------------------------------------------------------
  9779. function openAddCommunityListModal() {
  9780. document.getElementById('modal-rf-cl-id').value = '';
  9781. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  9782. document.getElementById('modal-rf-cl-name').value = '';
  9783. document.getElementById('modal-rf-cl-communities').value = '';
  9784. document.getElementById('modal-rf-cl-regexp').value = '';
  9785. document.getElementById('modal-rf-cl-comment').value = '';
  9786. document.getElementById('modal-rf-cl-disabled').checked = false;
  9787. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9788. }
  9789. function openEditCommunityListModal(id) {
  9790. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  9791. if (!cl) return;
  9792. document.getElementById('modal-rf-cl-id').value = cl.id;
  9793. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  9794. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  9795. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  9796. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  9797. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  9798. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  9799. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9800. }
  9801. function closeCommunityListModal() {
  9802. document.getElementById('modal-rf-community-list').classList.add('hidden');
  9803. }
  9804. async function submitCommunityList(e) {
  9805. e.preventDefault();
  9806. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  9807. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  9808. const payload = {
  9809. id: document.getElementById('modal-rf-cl-id').value,
  9810. name: document.getElementById('modal-rf-cl-name').value.trim(),
  9811. communities: comms,
  9812. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  9813. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  9814. disabled: document.getElementById('modal-rf-cl-disabled').checked
  9815. };
  9816. try {
  9817. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  9818. method: 'POST',
  9819. headers: { 'Content-Type': 'application/json' },
  9820. body: JSON.stringify(payload)
  9821. });
  9822. if (res.ok) {
  9823. closeCommunityListModal();
  9824. showToast('Success', 'Community list saved', 'success');
  9825. loadDynamicRouting();
  9826. } else {
  9827. const err = await res.json();
  9828. showToast('Error', err.error || 'Failed to save community list', 'error');
  9829. }
  9830. } catch (err) {
  9831. showToast('Error', err.message, 'error');
  9832. }
  9833. }
  9834. async function deleteCommunityList(id) {
  9835. if (!confirm('Are you sure you want to delete this community list?')) return;
  9836. try {
  9837. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9838. if (res.ok) {
  9839. showToast('Deleted', 'Community list removed', 'info');
  9840. loadDynamicRouting();
  9841. } else {
  9842. const err = await res.json();
  9843. showToast('Error', err.error || 'Failed to delete community list', 'error');
  9844. }
  9845. } catch (err) {
  9846. showToast('Error', err.message, 'error');
  9847. }
  9848. }
  9849. async function toggleCommunityListState(id, disabled) {
  9850. try {
  9851. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  9852. method: 'POST',
  9853. headers: { 'Content-Type': 'application/json' },
  9854. body: JSON.stringify({ disabled })
  9855. });
  9856. if (res.ok) {
  9857. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9858. loadDynamicRouting();
  9859. } else {
  9860. const err = await res.json();
  9861. showToast('Error', err.error || 'Failed to update community list state', 'error');
  9862. }
  9863. } catch (err) {
  9864. showToast('Error', err.message, 'error');
  9865. }
  9866. }
  9867. // -------------------------------------------------------------
  9868. // MODAL CRUD: AS LISTS (/routing filter num-list)
  9869. // -------------------------------------------------------------
  9870. function openAddASListModal() {
  9871. document.getElementById('modal-rf-al-id').value = '';
  9872. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  9873. document.getElementById('modal-rf-al-name').value = '';
  9874. document.getElementById('modal-rf-al-range').value = '';
  9875. document.getElementById('modal-rf-al-comment').value = '';
  9876. document.getElementById('modal-rf-al-disabled').checked = false;
  9877. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9878. }
  9879. function openEditASListModal(id) {
  9880. const al = (state.routingASLists || []).find(item => item.id === id);
  9881. if (!al) return;
  9882. document.getElementById('modal-rf-al-id').value = al.id;
  9883. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  9884. document.getElementById('modal-rf-al-name').value = al.name || '';
  9885. document.getElementById('modal-rf-al-range').value = al.range || '';
  9886. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  9887. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  9888. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9889. }
  9890. function closeASListModal() {
  9891. document.getElementById('modal-rf-as-list').classList.add('hidden');
  9892. }
  9893. async function submitASList(e) {
  9894. e.preventDefault();
  9895. const payload = {
  9896. id: document.getElementById('modal-rf-al-id').value,
  9897. name: document.getElementById('modal-rf-al-name').value.trim(),
  9898. range: document.getElementById('modal-rf-al-range').value.trim(),
  9899. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  9900. disabled: document.getElementById('modal-rf-al-disabled').checked
  9901. };
  9902. try {
  9903. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  9904. method: 'POST',
  9905. headers: { 'Content-Type': 'application/json' },
  9906. body: JSON.stringify(payload)
  9907. });
  9908. if (res.ok) {
  9909. closeASListModal();
  9910. showToast('Success', 'AS number list saved', 'success');
  9911. loadDynamicRouting();
  9912. } else {
  9913. const err = await res.json();
  9914. showToast('Error', err.error || 'Failed to save AS list', 'error');
  9915. }
  9916. } catch (err) {
  9917. showToast('Error', err.message, 'error');
  9918. }
  9919. }
  9920. async function deleteASList(id) {
  9921. if (!confirm('Are you sure you want to delete this AS list?')) return;
  9922. try {
  9923. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9924. if (res.ok) {
  9925. showToast('Deleted', 'AS list removed', 'info');
  9926. loadDynamicRouting();
  9927. } else {
  9928. const err = await res.json();
  9929. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  9930. }
  9931. } catch (err) {
  9932. showToast('Error', err.message, 'error');
  9933. }
  9934. }
  9935. async function toggleASListState(id, disabled) {
  9936. try {
  9937. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  9938. method: 'POST',
  9939. headers: { 'Content-Type': 'application/json' },
  9940. body: JSON.stringify({ disabled })
  9941. });
  9942. if (res.ok) {
  9943. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9944. loadDynamicRouting();
  9945. } else {
  9946. const err = await res.json();
  9947. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  9948. }
  9949. } catch (err) {
  9950. showToast('Error', err.message, 'error');
  9951. }
  9952. }
  9953. // ==========================================
  9954. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  9955. // ==========================================
  9956. function loadToolsView() {
  9957. populateToolsInterfaces();
  9958. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  9959. }
  9960. function populateToolsInterfaces() {
  9961. const pingSel = document.getElementById('tools-ping-iface');
  9962. const traceSel = document.getElementById('tools-tr-iface');
  9963. let opts = '<option value="">Auto (Default Route)</option>';
  9964. if (Array.isArray(state.interfaces)) {
  9965. state.interfaces.forEach(iface => {
  9966. if (iface.name) {
  9967. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  9968. }
  9969. });
  9970. }
  9971. if (pingSel) {
  9972. const cur = pingSel.value;
  9973. pingSel.innerHTML = opts;
  9974. if (cur) pingSel.value = cur;
  9975. }
  9976. if (traceSel) {
  9977. const cur = traceSel.value;
  9978. traceSel.innerHTML = opts;
  9979. if (cur) traceSel.value = cur;
  9980. }
  9981. }
  9982. function switchToolsSubTab(subTab) {
  9983. state.activeToolsSubTab = subTab;
  9984. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  9985. tabs.forEach(t => {
  9986. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  9987. const view = document.getElementById(`tools-view-${t}`);
  9988. if (btn) {
  9989. if (t === subTab) {
  9990. 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';
  9991. } else {
  9992. 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';
  9993. }
  9994. }
  9995. if (view) {
  9996. if (t === subTab) {
  9997. view.classList.remove('hidden');
  9998. } else {
  9999. view.classList.add('hidden');
  10000. }
  10001. }
  10002. });
  10003. }
  10004. function setPortPreset(port) {
  10005. const input = document.getElementById('tools-port-num');
  10006. if (input) input.value = port;
  10007. }
  10008. let pingAbortController = null;
  10009. let tracerouteAbortController = null;
  10010. function clearPingTable() {
  10011. const tbody = document.getElementById('tools-ping-tbody');
  10012. if (tbody) tbody.innerHTML = '';
  10013. const rawEl = document.getElementById('tools-ping-raw');
  10014. if (rawEl) rawEl.innerText = '';
  10015. const sentEl = document.getElementById('tools-ping-stat-sent');
  10016. if (sentEl) sentEl.innerText = '0';
  10017. const recvEl = document.getElementById('tools-ping-stat-recv');
  10018. if (recvEl) recvEl.innerText = '0';
  10019. const lossEl = document.getElementById('tools-ping-stat-loss');
  10020. if (lossEl) lossEl.innerText = '0%';
  10021. const avgEl = document.getElementById('tools-ping-stat-avg');
  10022. if (avgEl) avgEl.innerText = '0 ms';
  10023. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10024. if (minMaxEl) minMaxEl.innerText = '-';
  10025. const badge = document.getElementById('tools-ping-status-badge');
  10026. if (badge) {
  10027. badge.className = '';
  10028. badge.innerText = '';
  10029. }
  10030. }
  10031. function clearTracerouteTable() {
  10032. const tbody = document.getElementById('tools-tr-tbody');
  10033. if (tbody) tbody.innerHTML = '';
  10034. const rawEl = document.getElementById('tools-tr-raw');
  10035. if (rawEl) rawEl.innerText = '';
  10036. const statHops = document.getElementById('tools-tr-hops-count');
  10037. if (statHops) statHops.innerText = '0 Hops';
  10038. }
  10039. function resetPingButton() {
  10040. const btn = document.getElementById('tools-ping-btn');
  10041. const btnText = document.getElementById('tools-ping-btn-text');
  10042. const spinner = document.getElementById('tools-ping-spinner');
  10043. if (btn) {
  10044. btn.disabled = false;
  10045. 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';
  10046. }
  10047. if (btnText) btnText.innerText = 'Start Ping';
  10048. if (spinner) spinner.classList.add('hidden');
  10049. }
  10050. function setPingRunningButton() {
  10051. const btn = document.getElementById('tools-ping-btn');
  10052. const btnText = document.getElementById('tools-ping-btn-text');
  10053. const spinner = document.getElementById('tools-ping-spinner');
  10054. if (btn) {
  10055. btn.disabled = false;
  10056. 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';
  10057. }
  10058. if (btnText) btnText.innerText = 'Stop Ping';
  10059. if (spinner) spinner.classList.remove('hidden');
  10060. }
  10061. function resetTracerouteButton() {
  10062. const btn = document.getElementById('tools-tr-btn');
  10063. const btnText = document.getElementById('tools-tr-btn-text');
  10064. const spinner = document.getElementById('tools-tr-spinner');
  10065. if (btn) {
  10066. btn.disabled = false;
  10067. 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';
  10068. }
  10069. if (btnText) btnText.innerText = 'Start Traceroute';
  10070. if (spinner) spinner.classList.add('hidden');
  10071. }
  10072. function setTracerouteRunningButton() {
  10073. const btn = document.getElementById('tools-tr-btn');
  10074. const btnText = document.getElementById('tools-tr-btn-text');
  10075. const spinner = document.getElementById('tools-tr-spinner');
  10076. if (btn) {
  10077. btn.disabled = false;
  10078. 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';
  10079. }
  10080. if (btnText) btnText.innerText = 'Stop Traceroute';
  10081. if (spinner) spinner.classList.remove('hidden');
  10082. }
  10083. async function executePing(e) {
  10084. if (e) e.preventDefault();
  10085. // If already running, clicking the button stops the stream!
  10086. if (pingAbortController) {
  10087. pingAbortController.abort();
  10088. pingAbortController = null;
  10089. resetPingButton();
  10090. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10091. return;
  10092. }
  10093. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10094. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10095. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10096. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10097. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10098. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10099. if (!target) {
  10100. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10101. return;
  10102. }
  10103. clearPingTable();
  10104. const resCard = document.getElementById('tools-ping-results');
  10105. if (resCard) resCard.classList.remove('hidden');
  10106. pingAbortController = new AbortController();
  10107. setPingRunningButton();
  10108. try {
  10109. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10110. method: 'POST',
  10111. headers: { 'Content-Type': 'application/json' },
  10112. body: JSON.stringify({
  10113. target,
  10114. count,
  10115. size,
  10116. timeout,
  10117. interface: iface,
  10118. dont_frag: dontFrag
  10119. }),
  10120. signal: pingAbortController.signal
  10121. });
  10122. if (!res.ok) {
  10123. const errText = await res.text();
  10124. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10125. resetPingButton();
  10126. pingAbortController = null;
  10127. return;
  10128. }
  10129. const reader = res.body.getReader();
  10130. const decoder = new TextDecoder('utf-8');
  10131. let buffer = '';
  10132. while (true) {
  10133. const { done, value } = await reader.read();
  10134. if (done) break;
  10135. buffer += decoder.decode(value, { stream: true });
  10136. const blocks = buffer.split('\n\n');
  10137. buffer = blocks.pop() || '';
  10138. for (const block of blocks) {
  10139. const trimmed = block.trim();
  10140. if (!trimmed) continue;
  10141. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10142. try {
  10143. const evt = JSON.parse(line);
  10144. handleLivePingEvent(evt);
  10145. } catch (parseErr) {
  10146. console.warn('Ping SSE parse error:', parseErr, line);
  10147. }
  10148. }
  10149. }
  10150. } catch (err) {
  10151. if (err.name === 'AbortError') {
  10152. // User aborted normally
  10153. } else {
  10154. showToast('Ping Error', err.message, 'error');
  10155. }
  10156. } finally {
  10157. pingAbortController = null;
  10158. resetPingButton();
  10159. }
  10160. }
  10161. function handleLivePingEvent(evt) {
  10162. const sentEl = document.getElementById('tools-ping-stat-sent');
  10163. const recvEl = document.getElementById('tools-ping-stat-recv');
  10164. const lossEl = document.getElementById('tools-ping-stat-loss');
  10165. const avgEl = document.getElementById('tools-ping-stat-avg');
  10166. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10167. const badge = document.getElementById('tools-ping-status-badge');
  10168. const tbody = document.getElementById('tools-ping-tbody');
  10169. const rawEl = document.getElementById('tools-ping-raw');
  10170. if (evt.raw && rawEl) {
  10171. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10172. rawEl.scrollTop = rawEl.scrollHeight;
  10173. }
  10174. if (evt.type === 'reply') {
  10175. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10176. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10177. if (lossEl && evt.packet_loss_pct !== undefined) {
  10178. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10179. lossEl.className = evt.packet_loss_pct === 0
  10180. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10181. : (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');
  10182. }
  10183. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10184. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10185. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10186. }
  10187. if (badge) {
  10188. if (evt.packet_loss_pct === 0) {
  10189. 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';
  10190. badge.innerText = '100% OK';
  10191. } else {
  10192. 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';
  10193. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10194. }
  10195. }
  10196. if (tbody) {
  10197. const tr = document.createElement('tr');
  10198. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10199. tr.innerHTML = `
  10200. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10201. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10202. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10203. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10204. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10205. <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>
  10206. `;
  10207. tbody.appendChild(tr);
  10208. }
  10209. } else if (evt.type === 'timeout') {
  10210. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10211. if (lossEl && evt.packet_loss_pct !== undefined) {
  10212. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10213. 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';
  10214. }
  10215. if (badge) {
  10216. 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';
  10217. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10218. }
  10219. if (tbody) {
  10220. const tr = document.createElement('tr');
  10221. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10222. tr.innerHTML = `
  10223. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10224. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10225. <td class="py-2 px-3 text-slate-600">--</td>
  10226. <td class="py-2 px-3 text-slate-600">--</td>
  10227. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10228. <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>
  10229. `;
  10230. tbody.appendChild(tr);
  10231. }
  10232. } else if (evt.type === 'unreach') {
  10233. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10234. if (lossEl && evt.packet_loss_pct !== undefined) {
  10235. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10236. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10237. }
  10238. if (badge) {
  10239. 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';
  10240. badge.innerText = 'UNREACHABLE';
  10241. }
  10242. if (tbody) {
  10243. const tr = document.createElement('tr');
  10244. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10245. tr.innerHTML = `
  10246. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10247. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10248. <td class="py-2 px-3 text-slate-600">--</td>
  10249. <td class="py-2 px-3 text-slate-600">--</td>
  10250. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10251. <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>
  10252. `;
  10253. tbody.appendChild(tr);
  10254. }
  10255. } else if (evt.type === 'stats') {
  10256. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10257. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10258. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10259. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10260. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10261. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10262. }
  10263. } else if (evt.type === 'done') {
  10264. 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');
  10265. }
  10266. }
  10267. async function executeTraceroute(e) {
  10268. if (e) e.preventDefault();
  10269. if (tracerouteAbortController) {
  10270. tracerouteAbortController.abort();
  10271. tracerouteAbortController = null;
  10272. resetTracerouteButton();
  10273. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10274. return;
  10275. }
  10276. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10277. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10278. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10279. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10280. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10281. if (!target) {
  10282. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10283. return;
  10284. }
  10285. clearTracerouteTable();
  10286. const resCard = document.getElementById('tools-tr-results');
  10287. if (resCard) resCard.classList.remove('hidden');
  10288. tracerouteAbortController = new AbortController();
  10289. setTracerouteRunningButton();
  10290. try {
  10291. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10292. method: 'POST',
  10293. headers: { 'Content-Type': 'application/json' },
  10294. body: JSON.stringify({
  10295. target,
  10296. max_hops: maxHops,
  10297. protocol,
  10298. interface: iface,
  10299. resolve
  10300. }),
  10301. signal: tracerouteAbortController.signal
  10302. });
  10303. if (!res.ok) {
  10304. const errText = await res.text();
  10305. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10306. resetTracerouteButton();
  10307. tracerouteAbortController = null;
  10308. return;
  10309. }
  10310. const reader = res.body.getReader();
  10311. const decoder = new TextDecoder('utf-8');
  10312. let buffer = '';
  10313. while (true) {
  10314. const { done, value } = await reader.read();
  10315. if (done) break;
  10316. buffer += decoder.decode(value, { stream: true });
  10317. const blocks = buffer.split('\n\n');
  10318. buffer = blocks.pop() || '';
  10319. for (const block of blocks) {
  10320. const trimmed = block.trim();
  10321. if (!trimmed) continue;
  10322. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10323. try {
  10324. const evt = JSON.parse(line);
  10325. handleLiveTracerouteEvent(evt);
  10326. } catch (parseErr) {
  10327. console.warn('Traceroute SSE parse error:', parseErr, line);
  10328. }
  10329. }
  10330. }
  10331. } catch (err) {
  10332. if (err.name === 'AbortError') {
  10333. // User aborted normally
  10334. } else {
  10335. showToast('Traceroute Error', err.message, 'error');
  10336. }
  10337. } finally {
  10338. tracerouteAbortController = null;
  10339. resetTracerouteButton();
  10340. }
  10341. }
  10342. function handleLiveTracerouteEvent(evt) {
  10343. const statHops = document.getElementById('tools-tr-hops-count');
  10344. const tbody = document.getElementById('tools-tr-tbody');
  10345. const rawEl = document.getElementById('tools-tr-raw');
  10346. if (evt.raw && rawEl) {
  10347. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10348. rawEl.scrollTop = rawEl.scrollHeight;
  10349. }
  10350. if (evt.hops_count !== undefined && statHops) {
  10351. statHops.innerText = `${evt.hops_count} Hops`;
  10352. }
  10353. if (evt.type === 'hop' && evt.hop && tbody) {
  10354. const h = evt.hop;
  10355. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10356. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10357. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10358. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10359. const tr = document.createElement('tr');
  10360. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10361. tr.innerHTML = `
  10362. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10363. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10364. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10365. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10366. <td class="py-2.5 px-3 text-right">
  10367. ${isTimeout
  10368. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10369. : '<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>'}
  10370. </td>
  10371. `;
  10372. tbody.appendChild(tr);
  10373. } else if (evt.type === 'done') {
  10374. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10375. }
  10376. }
  10377. async function executeMTR(e) {
  10378. if (e) e.preventDefault();
  10379. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10380. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10381. if (!target) {
  10382. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10383. return;
  10384. }
  10385. const btn = document.getElementById('tools-mtr-btn');
  10386. const spinner = document.getElementById('tools-mtr-spinner');
  10387. if (btn) btn.disabled = true;
  10388. if (spinner) spinner.classList.remove('hidden');
  10389. try {
  10390. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10391. method: 'POST',
  10392. headers: { 'Content-Type': 'application/json' },
  10393. body: JSON.stringify({ target, count: cycles })
  10394. });
  10395. const data = await res.json();
  10396. if (!res.ok) {
  10397. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10398. return;
  10399. }
  10400. const resCard = document.getElementById('tools-mtr-results');
  10401. if (resCard) resCard.classList.remove('hidden');
  10402. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10403. const statHops = document.getElementById('tools-mtr-hops-count');
  10404. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10405. const tbody = document.getElementById('tools-mtr-tbody');
  10406. if (tbody) {
  10407. if (hopsCount > 0) {
  10408. tbody.innerHTML = data.hops.map(h => {
  10409. 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');
  10410. return `
  10411. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10412. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10413. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10414. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10415. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10416. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10417. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10418. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10419. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10420. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10421. </tr>
  10422. `;
  10423. }).join('');
  10424. } else {
  10425. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10426. }
  10427. }
  10428. const rawEl = document.getElementById('tools-mtr-raw');
  10429. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10430. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10431. } catch (err) {
  10432. showToast('MTR Error', err.message, 'error');
  10433. } finally {
  10434. if (btn) btn.disabled = false;
  10435. if (spinner) spinner.classList.add('hidden');
  10436. }
  10437. }
  10438. async function executeDNS(e) {
  10439. if (e) e.preventDefault();
  10440. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10441. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10442. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10443. if (!domain) {
  10444. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10445. return;
  10446. }
  10447. const btn = document.getElementById('tools-dns-btn');
  10448. const spinner = document.getElementById('tools-dns-spinner');
  10449. if (btn) btn.disabled = true;
  10450. if (spinner) spinner.classList.remove('hidden');
  10451. try {
  10452. const res = await fetch(`${API_BASE}/tools/dns`, {
  10453. method: 'POST',
  10454. headers: { 'Content-Type': 'application/json' },
  10455. body: JSON.stringify({ domain, type, server })
  10456. });
  10457. const data = await res.json();
  10458. if (!res.ok) {
  10459. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10460. return;
  10461. }
  10462. const resCard = document.getElementById('tools-dns-results');
  10463. if (resCard) resCard.classList.remove('hidden');
  10464. const metaEl = document.getElementById('tools-dns-meta');
  10465. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10466. const tbody = document.getElementById('tools-dns-tbody');
  10467. if (tbody) {
  10468. if (Array.isArray(data.records) && data.records.length > 0) {
  10469. tbody.innerHTML = data.records.map(r => `
  10470. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10471. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10472. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10473. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10474. <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>
  10475. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10476. </tr>
  10477. `).join('');
  10478. } else {
  10479. 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>`;
  10480. }
  10481. }
  10482. const rawEl = document.getElementById('tools-dns-raw');
  10483. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10484. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10485. } catch (err) {
  10486. showToast('DNS Error', err.message, 'error');
  10487. } finally {
  10488. if (btn) btn.disabled = false;
  10489. if (spinner) spinner.classList.add('hidden');
  10490. }
  10491. }
  10492. async function executePortProbe(e) {
  10493. if (e) e.preventDefault();
  10494. const target = document.getElementById('tools-port-target')?.value?.trim();
  10495. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10496. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10497. if (!target || !port) {
  10498. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10499. return;
  10500. }
  10501. const btn = document.getElementById('tools-port-btn');
  10502. const spinner = document.getElementById('tools-port-spinner');
  10503. if (btn) btn.disabled = true;
  10504. if (spinner) spinner.classList.remove('hidden');
  10505. try {
  10506. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10507. method: 'POST',
  10508. headers: { 'Content-Type': 'application/json' },
  10509. body: JSON.stringify({ target, port, timeout })
  10510. });
  10511. const data = await res.json();
  10512. if (!res.ok) {
  10513. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10514. return;
  10515. }
  10516. const resCard = document.getElementById('tools-port-results');
  10517. if (resCard) resCard.classList.remove('hidden');
  10518. const banner = document.getElementById('tools-port-banner');
  10519. const icon = document.getElementById('tools-port-icon');
  10520. const title = document.getElementById('tools-port-title');
  10521. const sub = document.getElementById('tools-port-sub');
  10522. const latency = document.getElementById('tools-port-latency');
  10523. if (data.open) {
  10524. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10525. if (icon) {
  10526. 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';
  10527. icon.innerText = '✓';
  10528. }
  10529. if (title) {
  10530. title.className = 'text-sm font-bold text-emerald-300';
  10531. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10532. }
  10533. if (sub) {
  10534. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10535. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10536. }
  10537. if (latency) {
  10538. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10539. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10540. }
  10541. } else {
  10542. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10543. if (icon) {
  10544. 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';
  10545. icon.innerText = '✕';
  10546. }
  10547. if (title) {
  10548. title.className = 'text-sm font-bold text-rose-300';
  10549. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10550. }
  10551. if (sub) {
  10552. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10553. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10554. }
  10555. if (latency) {
  10556. latency.className = 'text-base font-bold font-mono text-slate-500';
  10557. latency.innerText = '--';
  10558. }
  10559. }
  10560. const rawEl = document.getElementById('tools-port-raw');
  10561. 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'}`);
  10562. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10563. } catch (err) {
  10564. showToast('Probe Error', err.message, 'error');
  10565. } finally {
  10566. if (btn) btn.disabled = false;
  10567. if (spinner) spinner.classList.add('hidden');
  10568. }
  10569. }
  10570. // ==========================================
  10571. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10572. // ==========================================
  10573. async function loadDHCPClients(showToastMsg = false) {
  10574. try {
  10575. const [clientsRes, sumRes] = await Promise.all([
  10576. fetch(`${API_BASE}/dhcp/clients`),
  10577. fetch(`${API_BASE}/dhcp/clients/summary`)
  10578. ]);
  10579. if (clientsRes.ok) {
  10580. state.dhcpClients = await clientsRes.json();
  10581. }
  10582. if (sumRes.ok) {
  10583. state.dhcpSummary = await sumRes.json();
  10584. }
  10585. renderDHCPClients();
  10586. updateDHCPSummaryCards();
  10587. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10588. if (bDhcp && state.dhcpSummary) {
  10589. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10590. }
  10591. if (showToastMsg) {
  10592. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10593. }
  10594. } catch (err) {
  10595. console.error('Failed to load DHCP clients:', err);
  10596. if (showToastMsg) {
  10597. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10598. }
  10599. }
  10600. }
  10601. function updateDHCPSummaryCards() {
  10602. const sum = state.dhcpSummary || {
  10603. total_clients: (state.dhcpClients || []).length,
  10604. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10605. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10606. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10607. };
  10608. const totalEl = document.getElementById('dhcp-stat-total');
  10609. const boundEl = document.getElementById('dhcp-stat-bound');
  10610. const searchEl = document.getElementById('dhcp-stat-searching');
  10611. const disEl = document.getElementById('dhcp-stat-disabled');
  10612. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10613. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10614. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10615. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10616. }
  10617. function renderDHCPClients() {
  10618. const tbody = document.getElementById('dhcp-clients-tbody');
  10619. const emptyState = document.getElementById('dhcp-clients-empty');
  10620. if (!tbody) return;
  10621. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10622. if (clients.length === 0) {
  10623. tbody.innerHTML = '';
  10624. if (emptyState) emptyState.classList.remove('hidden');
  10625. return;
  10626. }
  10627. if (emptyState) emptyState.classList.add('hidden');
  10628. tbody.innerHTML = clients.map(c => {
  10629. let statusBadge = '';
  10630. if (!c.enabled) {
  10631. 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>';
  10632. } else if (c.status === 'bound') {
  10633. 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>';
  10634. } else if (c.status === 'searching') {
  10635. 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>';
  10636. } else if (c.status === 'stopped') {
  10637. 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>';
  10638. } else {
  10639. 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>`;
  10640. }
  10641. 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>';
  10642. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  10643. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  10644. 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>';
  10645. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  10646. // Option flags
  10647. const flags = [];
  10648. 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>');
  10649. 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>');
  10650. 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>');
  10651. 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>`);
  10652. return `
  10653. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  10654. <td class="py-3 px-4">
  10655. <div class="flex items-center gap-2">
  10656. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  10657. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  10658. </div>
  10659. </td>
  10660. <td class="py-3 px-4">${statusBadge}</td>
  10661. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  10662. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  10663. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  10664. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  10665. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  10666. <td class="py-3 px-4">
  10667. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  10668. </td>
  10669. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  10670. ${c.enabled ? `
  10671. <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>
  10672. <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>
  10673. <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>
  10674. ` : `
  10675. <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>
  10676. `}
  10677. <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>
  10678. <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>
  10679. </td>
  10680. </tr>
  10681. `;
  10682. }).join('');
  10683. }
  10684. function openDHCPClientModal(clientId = null) {
  10685. const modal = document.getElementById('modal-dhcp-client');
  10686. if (!modal) return;
  10687. const title = document.getElementById('modal-dhcp-title');
  10688. const idInput = document.getElementById('modal-dhcp-id');
  10689. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10690. const distInput = document.getElementById('modal-dhcp-distance');
  10691. const commentInput = document.getElementById('modal-dhcp-comment');
  10692. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  10693. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  10694. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  10695. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  10696. // Populate interfaces
  10697. if (ifaceSelect) {
  10698. let opts = '<option value="">Select interface...</option>';
  10699. const allIfaces = state.interfaces || [];
  10700. const allVlans = state.vlans || [];
  10701. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  10702. // Group 1: Physical & Bridge Interfaces
  10703. opts += '<optgroup label="Physical & Bridge Interfaces">';
  10704. allIfaces.forEach(i => {
  10705. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  10706. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  10707. });
  10708. opts += '</optgroup>';
  10709. // Group 2: VLAN Interfaces
  10710. if (allVlans.length > 0) {
  10711. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  10712. allVlans.forEach(v => {
  10713. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  10714. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  10715. });
  10716. opts += '</optgroup>';
  10717. }
  10718. ifaceSelect.innerHTML = opts;
  10719. }
  10720. if (clientId) {
  10721. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  10722. if (client) {
  10723. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  10724. if (idInput) idInput.value = client.id;
  10725. if (ifaceSelect) {
  10726. ifaceSelect.value = client.interface;
  10727. ifaceSelect.disabled = true; // interface cannot be changed on edit
  10728. }
  10729. if (distInput) distInput.value = client.default_route_distance || 1;
  10730. if (commentInput) commentInput.value = client.comment || '';
  10731. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  10732. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  10733. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  10734. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  10735. }
  10736. } else {
  10737. if (title) title.innerText = 'Add DHCP Client';
  10738. if (idInput) idInput.value = '';
  10739. if (ifaceSelect) {
  10740. ifaceSelect.value = '';
  10741. ifaceSelect.disabled = false;
  10742. }
  10743. if (distInput) distInput.value = 1;
  10744. if (commentInput) commentInput.value = '';
  10745. if (defRouteCheck) defRouteCheck.checked = true;
  10746. if (peerDnsCheck) peerDnsCheck.checked = true;
  10747. if (peerNtpCheck) peerNtpCheck.checked = true;
  10748. if (enabledCheck) enabledCheck.checked = true;
  10749. }
  10750. modal.classList.remove('hidden');
  10751. }
  10752. function openDHCPClientModalForIface(ifaceName) {
  10753. openDHCPClientModal();
  10754. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10755. if (ifaceSelect && ifaceName) {
  10756. ifaceSelect.value = ifaceName;
  10757. }
  10758. }
  10759. function closeDHCPClientModal() {
  10760. const modal = document.getElementById('modal-dhcp-client');
  10761. if (modal) modal.classList.add('hidden');
  10762. }
  10763. async function submitSaveDHCPClient(e) {
  10764. if (e) e.preventDefault();
  10765. const id = document.getElementById('modal-dhcp-id')?.value;
  10766. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  10767. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  10768. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  10769. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  10770. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  10771. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  10772. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  10773. if (!id && !iface) {
  10774. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  10775. return;
  10776. }
  10777. try {
  10778. let res;
  10779. if (id) {
  10780. // PUT update
  10781. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10782. method: 'PUT',
  10783. headers: { 'Content-Type': 'application/json' },
  10784. body: JSON.stringify({
  10785. enabled,
  10786. add_default_route: defRoute,
  10787. default_route_distance: distance,
  10788. use_peer_dns: peerDns,
  10789. use_peer_ntp: peerNtp,
  10790. comment
  10791. })
  10792. });
  10793. } else {
  10794. // POST create
  10795. res = await fetch(`${API_BASE}/dhcp/clients`, {
  10796. method: 'POST',
  10797. headers: { 'Content-Type': 'application/json' },
  10798. body: JSON.stringify({
  10799. interface: iface,
  10800. enabled,
  10801. add_default_route: defRoute,
  10802. default_route_distance: distance,
  10803. use_peer_dns: peerDns,
  10804. use_peer_ntp: peerNtp,
  10805. comment
  10806. })
  10807. });
  10808. }
  10809. const data = await res.json();
  10810. if (!res.ok) {
  10811. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  10812. return;
  10813. }
  10814. closeDHCPClientModal();
  10815. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  10816. await loadDHCPClients();
  10817. fetchData(); // refresh interfaces list with new lease/status
  10818. } catch (err) {
  10819. showToast('Error', err.message, 'error');
  10820. }
  10821. }
  10822. async function toggleDHCPClientState(id, enabled) {
  10823. try {
  10824. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  10825. method: 'POST',
  10826. headers: { 'Content-Type': 'application/json' },
  10827. body: JSON.stringify({ enabled })
  10828. });
  10829. const data = await res.json();
  10830. if (!res.ok) {
  10831. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  10832. return;
  10833. }
  10834. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  10835. await loadDHCPClients();
  10836. fetchData();
  10837. } catch (err) {
  10838. showToast('Error', err.message, 'error');
  10839. }
  10840. }
  10841. async function renewDHCPClient(id) {
  10842. try {
  10843. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  10844. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  10845. method: 'POST'
  10846. });
  10847. const data = await res.json();
  10848. if (!res.ok) {
  10849. showToast('Error', data.error || 'Failed to renew lease', 'error');
  10850. return;
  10851. }
  10852. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  10853. setTimeout(() => {
  10854. loadDHCPClients();
  10855. fetchData();
  10856. }, 1500);
  10857. } catch (err) {
  10858. showToast('Error', err.message, 'error');
  10859. }
  10860. }
  10861. async function releaseDHCPClient(id) {
  10862. try {
  10863. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  10864. method: 'POST'
  10865. });
  10866. const data = await res.json();
  10867. if (!res.ok) {
  10868. showToast('Error', data.error || 'Failed to release lease', 'error');
  10869. return;
  10870. }
  10871. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  10872. await loadDHCPClients();
  10873. fetchData();
  10874. } catch (err) {
  10875. showToast('Error', err.message, 'error');
  10876. }
  10877. }
  10878. async function deleteDHCPClient(id, ifaceName) {
  10879. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  10880. return;
  10881. }
  10882. try {
  10883. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10884. method: 'DELETE'
  10885. });
  10886. const data = await res.json();
  10887. if (!res.ok) {
  10888. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  10889. return;
  10890. }
  10891. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  10892. await loadDHCPClients();
  10893. fetchData();
  10894. } catch (err) {
  10895. showToast('Error', err.message, 'error');
  10896. }
  10897. }
  10898. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  10899. function initTableSorting() {
  10900. document.querySelectorAll('table').forEach(setupSortableTable);
  10901. }
  10902. function setupSortableTable(table) {
  10903. const thead = table.querySelector('thead');
  10904. const tbody = table.querySelector('tbody');
  10905. if (!thead || !tbody) return;
  10906. const headerRows = thead.querySelectorAll('tr');
  10907. if (headerRows.length === 0) return;
  10908. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  10909. ths.forEach((th, colIdx) => {
  10910. if (th._sortBound) return;
  10911. th._sortBound = true;
  10912. const rawText = th.innerText.trim().toLowerCase();
  10913. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  10914. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  10915. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  10916. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  10917. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  10918. return;
  10919. }
  10920. th.classList.add('table-sortable', 'group');
  10921. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  10922. let icon = th.querySelector('.table-sort-icon');
  10923. if (!icon) {
  10924. icon = document.createElement('span');
  10925. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10926. icon.innerHTML = '⇅';
  10927. th.appendChild(icon);
  10928. }
  10929. th.addEventListener('click', (e) => {
  10930. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  10931. handleHeaderClick(table, th, colIdx);
  10932. });
  10933. });
  10934. if (!tbody._sortObserved) {
  10935. tbody._sortObserved = true;
  10936. let sortDebounceTimer = null;
  10937. const observer = new MutationObserver((mutations) => {
  10938. if (tbody._isSorting) return;
  10939. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  10940. if (!hasChildChanges) return;
  10941. clearTimeout(sortDebounceTimer);
  10942. sortDebounceTimer = setTimeout(() => {
  10943. if (tbody._isSorting) return;
  10944. if (table._activeSort && table._activeSort.dir !== 'none') {
  10945. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  10946. } else {
  10947. tagOriginalRowOrder(tbody);
  10948. }
  10949. }, 10);
  10950. });
  10951. observer.observe(tbody, { childList: true });
  10952. }
  10953. tagOriginalRowOrder(tbody);
  10954. }
  10955. function tagOriginalRowOrder(tbody) {
  10956. let idx = 0;
  10957. Array.from(tbody.children).forEach(tr => {
  10958. if (!tr.querySelector('td[colspan]')) {
  10959. if (!tr.hasAttribute('data-orig-idx')) {
  10960. tr.setAttribute('data-orig-idx', idx++);
  10961. }
  10962. }
  10963. });
  10964. }
  10965. function handleHeaderClick(table, th, colIdx) {
  10966. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  10967. let newDir = 'asc';
  10968. if (currentSort.colIdx === colIdx) {
  10969. if (currentSort.dir === 'asc') newDir = 'desc';
  10970. else if (currentSort.dir === 'desc') newDir = 'none';
  10971. else newDir = 'asc';
  10972. } else {
  10973. newDir = 'asc';
  10974. }
  10975. table._activeSort = { colIdx, dir: newDir };
  10976. updateHeaderIcons(table, colIdx, newDir);
  10977. applyTableSort(table, colIdx, newDir, true);
  10978. }
  10979. function updateHeaderIcons(table, activeColIdx, dir) {
  10980. const thead = table.querySelector('thead');
  10981. if (!thead) return;
  10982. const ths = thead.querySelectorAll('th');
  10983. ths.forEach((th, idx) => {
  10984. const icon = th.querySelector('.table-sort-icon');
  10985. if (!icon) return;
  10986. if (idx === activeColIdx && dir !== 'none') {
  10987. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  10988. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  10989. th.classList.add('table-sorted-active');
  10990. } else {
  10991. icon.innerHTML = '⇅';
  10992. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10993. th.classList.remove('table-sorted-active');
  10994. }
  10995. });
  10996. }
  10997. function applyTableSort(table, colIdx, dir, userInitiated) {
  10998. const tbody = table.querySelector('tbody');
  10999. if (!tbody || tbody.children.length <= 1) return;
  11000. tbody._isSorting = true;
  11001. tagOriginalRowOrder(tbody);
  11002. // Group parent rows and any attached drawer/sub-rows
  11003. const groups = [];
  11004. let currentGroup = null;
  11005. Array.from(tbody.children).forEach(tr => {
  11006. if (tr.querySelector('td[colspan]')) {
  11007. if (currentGroup) {
  11008. currentGroup.subRows.push(tr);
  11009. } else {
  11010. groups.push({ mainRow: tr, subRows: [] });
  11011. }
  11012. } else {
  11013. currentGroup = { mainRow: tr, subRows: [] };
  11014. groups.push(currentGroup);
  11015. }
  11016. });
  11017. if (dir === 'none') {
  11018. groups.sort((a, b) => {
  11019. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11020. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11021. return idxA - idxB;
  11022. });
  11023. } else {
  11024. groups.sort((a, b) => {
  11025. const cellA = a.mainRow.children[colIdx];
  11026. const cellB = b.mainRow.children[colIdx];
  11027. const res = compareTableCells(cellA, cellB);
  11028. return dir === 'asc' ? res : -res;
  11029. });
  11030. }
  11031. // Re-append rows in sorted order
  11032. groups.forEach(g => {
  11033. tbody.appendChild(g.mainRow);
  11034. g.subRows.forEach(sub => tbody.appendChild(sub));
  11035. });
  11036. tbody._isSorting = false;
  11037. }
  11038. function getCellRawText(cell) {
  11039. if (!cell) return '';
  11040. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  11041. const input = cell.querySelector('input, select');
  11042. if (input) {
  11043. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  11044. return input.value;
  11045. }
  11046. return cell.innerText.trim();
  11047. }
  11048. function parseTrafficToNumber(str) {
  11049. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  11050. if (!m) return null;
  11051. const num = parseFloat(m[1].replace(/,/g, ''));
  11052. if (isNaN(num)) return null;
  11053. const unit = m[2].toUpperCase();
  11054. let mult = 1;
  11055. if (unit.startsWith('K')) mult = 1024;
  11056. else if (unit.startsWith('M')) mult = 1024 * 1024;
  11057. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  11058. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  11059. return num * mult;
  11060. }
  11061. function parseIpToNumber(str) {
  11062. const clean = str.replace(/^[!~]/, '').trim();
  11063. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  11064. if (!m) return null;
  11065. const o1 = parseInt(m[1], 10);
  11066. const o2 = parseInt(m[2], 10);
  11067. const o3 = parseInt(m[3], 10);
  11068. const o4 = parseInt(m[4], 10);
  11069. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  11070. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  11071. }
  11072. function parseCompoundPackets(str) {
  11073. const m = str.match(/^([\d,]+)p/);
  11074. if (!m) return null;
  11075. return parseInt(m[1].replace(/,/g, ''), 10);
  11076. }
  11077. function compareTableCells(cellA, cellB) {
  11078. const a = getCellRawText(cellA);
  11079. const b = getCellRawText(cellB);
  11080. if (a === '' && b !== '') return 1;
  11081. if (b === '' && a !== '') return -1;
  11082. if (a === b) return 0;
  11083. // 1. IP Addresses / CIDR
  11084. const ipA = parseIpToNumber(a);
  11085. const ipB = parseIpToNumber(b);
  11086. if (ipA !== null && ipB !== null) return ipA - ipB;
  11087. // 2. Packet counts (e.g. "1,250p / 45 KB")
  11088. const pktA = parseCompoundPackets(a);
  11089. const pktB = parseCompoundPackets(b);
  11090. if (pktA !== null && pktB !== null) return pktA - pktB;
  11091. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  11092. const trafA = parseTrafficToNumber(a);
  11093. const trafB = parseTrafficToNumber(b);
  11094. if (trafA !== null && trafB !== null) return trafA - trafB;
  11095. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  11096. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11097. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11098. const numA = Number(cleanNumA);
  11099. const numB = Number(cleanNumB);
  11100. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  11101. return numA - numB;
  11102. }
  11103. // 5. Natural case-insensitive string compare
  11104. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  11105. }
  11106. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11107. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11108. const docTableObserver = new MutationObserver((mutations) => {
  11109. let needsInit = false;
  11110. for (const m of mutations) {
  11111. for (const node of m.addedNodes) {
  11112. if (node.nodeType === 1) {
  11113. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11114. needsInit = true;
  11115. break;
  11116. }
  11117. }
  11118. }
  11119. if (needsInit) break;
  11120. }
  11121. if (needsInit) {
  11122. initTableSorting();
  11123. }
  11124. });
  11125. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11126. }